I ran across this puzzle today. Obviously, this isn't correct style, but I'm still curious as to why no output is coming out.
int x = 9;
int y = 8;
int z = 7;
if (x > 9) if (y > 8) System.out.println("x > 9 and y > 8");
else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
The above has no output when run. But, when we add in brackets for the if-statement, suddenly the logic behaves as I expect.
int x = 9;
int y = 8;
int z = 7;
if (x > 9) {
if (y > 8) System.out.println("x > 9 and y > 8");
}
else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
This outputs "SHOULD OUTPUT THIS x <= 9 and z >= 7". What is going on here?
Thanks!
else
applies to the inner-most nesting level.