Java Reference
In-Depth Information
The
for
-
each
loop uses the same
for
keyword used by the basic
for
loop. Its body is executed as many times
as the number of elements in the
array. DataType e
is a variable declaration, where
e
is the variable name and
DataType
is its data type. The data type of the variable
e
should be assignment-compatible with the type of the
array
.
The variable declaration is followed by a colon (
:
), which is followed by the reference of the array that you want to
loop through. The
for
-
each
loop assigns the value of an element of the array to the variable
e
, which you can use
inside the body of the loop. The following snippet of code uses a
for
-
each
loop to print all elements of an
int
array:
int[] numList = {1, 2, 3};
for(int num : numList) {
System.out.println(num);
}
1
2
3
You can accomplish the same thing using the basic
for
loop, as follows:
int[] numList = {1, 2, 3};
for(int i = 0; i < numList.length; i++) {
int num = numList[i];
System.out.println(num);
}
1
2
3
Note that the
for
-
each
loop provides a way to loop through elements of an array, which is cleaner than the basic
for
loop. However, it is not a replacement for the basic
for
loop because you cannot use it in all circumstances. For
example, you cannot access the index of the array element and you cannot modify the value of the element inside the
loop as you do not have the index of the element.
Array Declaration Syntax
You can declare an array by placing brackets (
[]
) after the data type of the array or after the name of the array
reference variable. For example, the following declaration
int[] empIds;
int[][] points2D;
int[][][] points3D;
Person[] persons;
is equivalent to
int empIds[];
int points2D[][];
int points3D[][][];
Person persons[];