A. Introduction
Take a look at the "else" statement in the code snippet below, which "if" statement does it match to?
double shippingCharge = 5.00; // $5 inside continental U.S.
if (country.equals("USA"))
if (state.equals("HI")) shippingCharge = 10.00; // Hawaii is more expensive
else // Pitfall!
shippingCharge = 20.00; // As are foreign shipments
The indentation level seems to suggest that the else is grouped with the test country. equals("USA"). Unfortunately, that is not the case. The compiler ignores all indentation and matches the else with the preceding if. That is, the code is actually
double shippingCharge = 5.00; // $5 inside continental U.S.
if (country.equals("USA"))
if (state.equals("HI"))
shippingCharge = 10.00; // Hawaii is more expensive
else // Pitfall!
shippingCharge = 20.00; // As are foreign shipments
That isn’t what we want. You want to group the else with the first if. The ambiguous else is called a dangling else. You can avoid this pitfall if you always use braces, as below:
double shippingCharge = 5.00; // $5 inside continental U.S.
if (country.equals("USA"))
{ // beginning of the if block
if (state.equals("HI")) { shippingCharge = 10.00; // Hawaii is more expensive }
} // end of the if block
else { shippingCharge = 20.00; // As are foreign shipments }
The brace in bold faces marks the beginning and end of the first "if" block, allows the "else" to match the first "if" instead of the second.
B. Notes : "else" is always matched to the closest "if block"