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

Given:

public class Test {
    public static void main(String[] args) {
        int x = 5;
        boolean b1 = true;
        boolean b2 = false;

        if ((x == 4) && !b2)
            System.out.print("1 ");
            System.out.print("2 ");
        if ((b2 = true) && b1)
            System.out.print("3 ");
    }
}

What is the result?


A. 2
B. 3
C. 1 2
D. 2 3
E. 1 2 3
F. Compilation fails.
G. An exception is thrown at runtime.

答案:


解析:

因為 if 後只有一個陳述句,可不使用{}將複合陳述句包括起來

所以System.out.print("2 ");並不在陳述句中喔

只要程式沒有編譯錯誤,就一定會印出2



另外雖然if 條件式內使用了指派符號(=)

但只要條件式能回傳布林值

就不會發生編譯錯誤



0 意見:

張貼留言