Control Structures: if Statements

if / else if / else Statements

The generalized grammar for if / else if / else statements is as follows. First, the series must begin with an if. You cannot begin with else if or else, they must be connected to a starting if. Second, if's and else if's must be followed directly by a set of parenthesis and a conditional expression within the parenthesis. Recall that a conditional expression will yield a true or false result or will simply be the literal true or false. The if, else if, and else will all be followed by a connected statement block, marked by the open and closing pair of curly brackets. Example syntax for each is listed here.

Example structure of an if by itself.
  if (expression) {
    // the statements to execute if expression is true
  }
Example structure of an if and else combination.
  if (expression) {
    // the statements to execute if expression is true
  }
  else {
    // the statements to execute if expression is false
  }
Example structure of an if, else if, else if, and else set.
  if (expression1) {
    // the statements to execute if expression1 is true
  }
  else if (expression2) {
    // the statements to execute if expression2 is true
  }
  // ...
  else if (expressionN) {
    // the statements to execute if expressionN is true
  }
  else {
    // the statements to execute if expression1, expression2, and expression3 are all false
  }
Here is an example code fragment of three independent if statements.
 if (number < 0) {
   System.out.println("Negative");
 }
 if (number < 100) {
   System.out.println("Less than 100");
 }
 if (number >= 100) {
   System.out.println("Great than or equal to 100");
 }
Here is the same set of boolean expressions included within a single, dependent if and else if combination.
 if (number < 0) {
   System.out.println("Negative");
 }
 else if (number < 100) {
   System.out.println("Less than 100");
 }
 else if (number >= 100) {
   System.out.println("Great than or equal to 100");
 }