Consider the following Java code:
int[] array = {1, 2, 3, 4, 5, 6};
for(int i : array) {
System.out.print(i + " ");
}
The above code obviously prints the contents of the array.
1 2 3 4 5
My question is why doesn't Java allow this?
int[] array = {1, 2, 3, 4, 5, 6};
int i;
for(i : array) {
System.out.print(i + " ");
}
EDIT: when I compile the 2nd program, I get the following error:
Main.java:14: error: bad initializer for for-loop
for(i : array) {
^
1 error