Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested if-else behaviour without braces

Consider the following unformatted nested if-else Java code

if (condition 1)
if (condition 2)
action 1;
else
action 2;

My question is: according to the Java language specifications, to what if does the else branch apply?

By hand-reformatting and adding braces, which of these two is correct?

Block 1:

if (condition 1) {
    if (condition 2) {
        action 1;
    } else
        action 2;
    }
}

Block 2:

if (condition 1) {
    if (condition 2) {
        action 1;
    }
}
else {
    action 2;
}
like image 510
usr-local-ΕΨΗΕΛΩΝ Avatar asked Jun 18 '13 15:06

usr-local-ΕΨΗΕΛΩΝ


People also ask

Do all if statements need braces?

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Does else if need brackets?

The else part of the if/else statement follows the same rules as the if part. If you want to execute multiple statements for the else condition, enclose the code in curly brackets. If you only need to execute a single statement for the else condition, you do not need to use curly brackets.

Do ELSE statements need curly braces?

For Java, curly braces are optional for if-else statements. As Jared stated, only the next statement will be executed when curly braces are omitted. Generally the braces help with organization and readability of the code, so they commonly will be used.

DO IF statements need curly braces C++?

Sometimes, you can write if statement without curly braces when only one statement follows the if condition. if(expression) statement1; There is no other statements to execute except statement1.


1 Answers

From the Java Language Specification:

The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong.

like image 154
Vincent van der Weele Avatar answered Oct 12 '22 18:10

Vincent van der Weele