A. Notes
Using array indices allows you to point to any array element instantly. This is just like when you buy tickets in a theater, the prices are associated with row numbers and column numbers. But sometimes, as in a graduation ceremony, everyone will stand up and walk to the podium on stage to get a certificate. In this case, each person gets the same treatment.
If we need to print out all elements in an array, we can use for-each loop without the index. Similarly, for 2-D arrays, we can use for-each loops to print one row at a time.
For-each loops are also called enhanced for loops.
Data elements of an array can only be accessed/examined in for-each loops, but they can't be modified or deleted. If you need to change data values, use regular for loops.
B. Examples
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {System.out.print( x + ",");} System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {System.out.print( name + ",");}
int[][] magic = { {16, 3, 2, 13}, {5, 10, 11, 8}, {9, 6, 7, 12}, {4, 15, 14, 1}};
for(int[] row : magic){
for(int x: row) {System.out.print( x + ",");} System.out.print("\n");
}
}
}