Home Segments Top Top Previous Next

392: Mainline

Although you can rely on the rule that an else statement belongs to the nearest unmatched if, it is better programming practice to use braces to avoid potential misreading.

In the following example, it is clear that the question mark should be replaced by "long", because the braces clearly group the else statement with the second if:

if (length > 60) { 
 if (length < 90)  
  System.out.println("It is normal!"); 
 else 
  System.out.println("It is ?"); 
} 

On the other hand, in the following example, it is clear that the question mark should be replaced by "short", because the braces clearly group the else statement with the first if:

if (length > 60) { 
 if (length < 90) 
  System.out.println("It is normal!"); 
} 
else 
 System.out.println("It is ?");