AbhishekC7 AbhishekC7 - 2 months ago 4x
Java Question

Nested if - else in java

I am preparing for the OCA 8 examination ...

There was a question in the enthuware test, what is the proper structure of the following code(like which if belongs to which else - without curly brackets)?


statement 1;
statement 2;
statement 3;
statement 4;


The answer provided in enthuware was like this ...

if //statement 1
| if //statement 2
| |
| else //statement 3
else //statement 4

but when I performed the code in the eclipse (without curly brackets), I got a compile time error in the last else...

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "else", delete this token

So, is this right/valid/possible?


If you do not put curly braces, only the first statement after if() is considered. In your case, the two if statements are nested but the first else statement is for the parent if, the second else hence is without an if.