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:
D) or am I missing something?
... the (x = false) is probably a typo, but has no influence on the result ...
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.
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.
Post a Comment