For and For Each Loop in Java Array


Array Length

In Java, we have a property length to know the size of array. We can easily know number of elements or size of the array. Syntax:

ArrayName.length
Example:
int[] mark = new int[5]; int size = mark.length; System.out.println("Size: " + size);
It will give us Size: 5 as output.

In last topic we learnt about how to insert data and how to access data in array. But if you remember we had to repeat same statement multiple times and our code was a bit longer. This is when loop comes in use.


For Loop in Array

We can use the value of iteration inside loop block. This plays main role to traverse(visit) array.

We can keep code inside loop block and use iteration value as index. So that it will visit all data. We can use length property to define how many times iteration should run.


Examples:

Lets display all data of array using for loop.
Code:

public class LearnArray { public static void main(String[] args) { int[] num = {21, 42, 33, 14, 35}; for(int i = 0; i < num.length; i++) { System.out.println("Index: "+ i + " Value: " + num[i]); } } }
Output:
Index: 0 Value: 21
Index: 1 Value: 42
Index: 2 Value: 33
Index: 3 Value: 14
Index: 4 Value: 35


Lets see another example where user can input their own data in array and print all data.
Code:

import java.util.Scanner; public class LearnArray { public static void main(String[] args) { Scanner inp = new Scanner(System.in); //create array int[] num = new int[5]; //insert data from user System.out.println("Enter data in array: "); for(int i = 0; i < num.length; i++) { num[i] = inp.nextInt(); } //display all data System.out.println("Array data are: "); for(int i = 0; i < num.length; i++) { System.out.println(num[i]); } } }
Output:
Enter data in array:
5
3
8
1
5
Array data are:
5
3
8
1
5


For Each Loop in Array

For Each Loop is specifically designed for traversing array. With the help of for each loop, we can visit all data of array.

It starts from very beginning of array and for each iteration it stores the data in new variable. Syntax:

for(DataType variable : Array) {
    statements here
}


Example:

Lets access all data of array using for each loop.
Code:

public class LearnArray { public static void main(String[] args) { int[] num = {3, 2, 8, 9, 10}; for(int i : num) { System.out.println(i); } } }
Output:
3
2
8
9
10
Note that variable datatype must be same as array data type.


Arrays in Java | Part 2 Previous Next Multidimensional Array in Java