I have a sample code which creates an "array" of size 10 and tries to initialize it with reverse values in a For loop e.g:(9,8,7,6,5...0):
int[] array = new int[10];
for (int i = array.length - 1, j = 0; i >= 0; i--, j++) {
System.out.println("Present value of i=" + i
+ " Present value of j=" + j);
array[j] = i;
System.out.println("Array:" + j + "=" + i);
}
for (int k : array) {
System.out.println(array[k]);
}
So far so good. This is the output from console which is perfect:
Present value of i=9 Present value of j=0
Array:0=9
Present value of i=8 Present value of j=1
Array:1=8
Present value of i=7 Present value of j=2
Array:2=7
Present value of i=6 Present value of j=3
Array:3=6
Present value of i=5 Present value of j=4
Array:4=5
Present value of i=4 Present value of j=5
Array:5=4
Present value of i=3 Present value of j=6
Array:6=3
Present value of i=2 Present value of j=7
Array:7=2
Present value of i=1 Present value of j=8
Array:8=1
Present value of i=0 Present value of j=9
Array:9=0
The issue is with For-each loop in the end which is just printing the values in array:
for (int k : array) {
System.out.println(array[k]);
}
The values printed array are 0,1,2...9 where it should be 9,8,7...0
When I use the regular For loop to print the array, it works normally. Am I missing some funny business here?
for (int k : array)mean? What doesarray[k]mean?for...inloop iterates keys of an object. Java's for-each loop only works with values; it has no concept of keys.forloops are pretty standard across languages. For-each loops, however, are pretty different across the board. Never assume a foreach loop works the same, or even exists, in another language! :)