What is the result of the following code compilation and execution?

public class Test {
    public static void main(String[] args) {
        for (final int i : new int[] { 1, 2, 3 }) {
            System.out.println(i + 1);
        }
    }
}
Explanation
This loop is unfolded by the compiler into a code doing this:

array = new int[] { 1, 2, 3 };
for(int index = 0; index < array.length; index
++) {
final int i = array[index];
...
}
i is a local variable, which, as expected, is initialized at the beginning of each iteration of the loop.
Java
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback