Introduction: 3.3.0

  • use if and else to pick between two possibilities
  • Can be used with relational operators
boolean myExpr = false;
if (myExpr) {
  doSomethingWhenTrue();
} else {
  doSomethingWhenFalse();
}

Nested ifs and Dangling else: 3.3.1

  • if statements can be nested
  • Can sometimes have “dangling else” which could belong to either
    • This always belongs to the closest if statement
      • Regardless of Indentation
    • Use curly brackets to differentiate
if (boolean)
  if (boolean)
    doSomething();
else // THIS BELONGS TO THE SECOND IF

if (boolean) {
  if (boolean)
    doSomething();
} else {
// BELONGS TO THE SECOND IF
}

Summary: 3.3.3

  • if statements can be followed by an else to make a 2-way branch
    • One executed when true, the other when false
  • Use 2 test-cases to test both branches and fine errors
  • else statements attach to the nearest if