Make Matches clear with Braces

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

Here is the example fragment properly indented and with matching ifs and elses colored the same.

if ( a == b )
  
  if ( d == e )
    total = 0;
  
  else
    total = total + a;

else
  total = total + b;

Make Matches clear with Braces

Sometimes you must use braces { and } to say what you want. An else inside of a pair of braces must match an if also inside that pair. Sometimes you don't need braces, but use them to make clear (to human readers) what you intend. Here is the complete rule for matching ifs and elses:

Rule for Matching if and else:   Within each pair of matching braces: start with the first if and work downward. Each else matches the closest previous unmatched if. An if matches only one else and an else matches only one if.

Here is a program fragment that uses braces:

if (  ch == 'q' )
{
    if ( sum == 12 )
          ch = 'b' ;
}
else
    ch = 'x' ; 

The blue if and blue else match. Without the braces, they would not match. Here is another, poorly indented, fragment:

if ( a == b )
{  
if ( d == e )
  total = 0;

else
  total = total + b;
}

QUESTION 13:

Match the ifs and elses.