Given:



public class Natural {

    private int i;

    void disp() {
        while (i <= 5) {
            for (int i = 1; i <= 5;) {
                System.out.print(i + " ");
                i++;
            }
            i++;
        }
    }

    public static void main(String[] args) {
        new Natural().disp();
    }
}

What is the result?

A. Prints 1 2 3 4 5 once
B. Prints 1 3 5 once
C. Prints 1 2 3 4 5 five times
D. Prints 1 2 3 4 5 six times
E. Compilation fails

題解

第3行宣告了物件變數i,第7行的for迴圈又宣告了一個變數i,因此for的變數i會遮蔽掉物件的變數i。無論for怎麼對它的變數i做任何更動,都不會影響到物件的變數i。

物件變數若沒有給定初始值,則預設為0。第6行開始的while迴圈與第11行的「i++;」決定了while迴圈的執行次數,i的變化為0,1,2,...,5,6,只有在小於等於5的時候才會執行while迴圈的內容,因此第7行的for迴圈被執行了6次。每執行一次for迴圈,會印出「1 2 3 4 5 」。