Tuesday, August 24, 2010

Pre/Post-Increment: Test4.java

Courtesy of Sun Web Learning Center

Given:

1.  class Test4 {
2.    public static void main(String [] args) {
3.      boolean x = true;
4.      boolean y = false;
5.      short z = 42;
6.
7.      if((z++ == 42) && (y = true))  z++;
8.      if((x = false) || (++z == 45)) z++;
9.
10.      System.out.println("z = " + z);
11.    }
12.  }
What is the result?


A z = 42
B z = 44
C z = 45
D z = 46
E Compilation fails.
F An exception is thrown at runtime.

D is correct. Line 7 does NOT test y, it sets it to true. Line 8 pre-increments z in the if test.

No comments:

Post a Comment