27 May 2009

SCJP - This one could knock me out

Can anyone solve this? I've chosen wrong :( And probably learned something.



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.

3 comments:

Unknown said...

D) or am I missing something?

... the (x = false) is probably a typo, but has no influence on the result ...

murdertreats said...

I would say compilation fails due to the ='s .

But assuming the ='s are typos not intended to be part of the test, I'd say this line:

if((z++ == 42) && (y = true)) z++;

tests (z == 42) finds it true, increments z from 42 to 43, continues to test (y==true), fails so jumps to the next if-statement, without incrementing z. Then this one:

if((x = false) || (++z == 45)) z++;

Tests (x == false), fails. Increments z from 43 to 44 then tests (z == 45), fails, making the entire if-statement fail, so jumps straight to

System.out.println("z = " + z);

printing z as 44. So answer B) in that case.

siwa said...

D) is correct. First I assumed that (y = true) would fail on compile time. But now I am aware of variable assigments within if statements and so on.