SCJP(OCPJP) 考古題解析 第22題

Given:

class Pass {
    public static void main(String[] args) {
        int x = 5;
        Pass p = new Pass();
        p.doStuff(x);
        System.out.print(" main x = " + x);
    }
    void doStuff(int x) {
        System.out.println(" doStuff x = " + x++);
    }
}

What is the result?


A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5

答案:



解析:

x++先参與算才再自行++


所以先印出 doStuff x = 5

且因doStuff()方法内的x++加到了 doStuff()方法的區變數x

不影主程式内的x


所以再印出 main x = 5




0 意見:

張貼留言