Witscale Test Center

5.2 Conditional statements: if, if-else and switch > 5.2.2 The if-else statement


5.2.2 The if-else statement

The if statement has an optional else clause which is used to write the alternate sequence if the condition specified in if statement is not true. For example,

 

if(a < 4) {

 System.out.println(“a is less than 4”);

}

else {

 System.out.println(“a is greater than or equal to 4”);

}

 

Like the if clause, the else clause may not use curly brackets. When they are not used, the next immediate statement is considered as part of their body. For instance, if the else statement (without curly brackets) is followed by another if-else block,  then this additional if-else block is part of that else.

Even if curly brackets are optional, it is recommended to use them. If you do not use them and the code is not properly indented, it is very difficult to understand the program flow. This is especially true with nested if-else statements. The nested if-else are setup to test multiple conditions. For example, if we are calculating tax, we can have multiple conditions that decide the ultimate flow for tax calculation. The following example demonstrates nested if and if-else statements.

 

 

if(isMarried) {

  if(wages > 30000) {

   calculateTaxForMarried();

  }

 }

else {

    if(isHeadOfHousehold){

     if(wages > 40000) {

       calculateTaxForHoH();

     }

    } else {

     calculateTaxForSingle();

    }

}

 

The nested if-else statements in the above code are quite readable due to proper indentation and curly brackets. However, they can be tough to understand if no indentation or curly brackets are used. The following code snippet shows the same code without curly brackets and indentation. 

 

if(isMarried)

if(wages > 30000)

calculateTaxForMarried();

else if(isHeadOfHousehold)

if(wages > 40000)

calculateTaxForHoH();

else

calculateTaxForSingle();

 

You possibly will have a hard time figuring out which else belongs to which if statement. Therefore, it is recommended to enclose the nested if-else properly in curly brackets to avoid any sort of confusion.

 

You need to be careful while dealing with nested if statements. When you face a code with nested if with no indentation and curly brackets, here is a rule of thumb.

1.       The else statement belongs to the immediately previous if statement.

2.       If no curly brackets are used after if statement then the ‘statement’ (which can be another if statement or if-else statement or even a nested if statement) next to the if statement  is executed when the condition in if statement is true.

Therefore the above code will be read by the compiler as:

if(isMarried)

 if(wages > 30000)

   calculateTaxForMarried();

 else

  if(isHeadOfHousehold)

   if(wages > 40000)

     calculateTaxForHoH();

   else

     calculateTaxForSingle();

Hence this code will be interpreted differently than the code we earlier wrote with curly brackets.