if-else-if statements

The if-else-if statement allows you to chain together two or more if statements such that the body of the first if-statement's condition that evaluates to true is executed, and none of the other if-statement bodies are. It is defined as this template (where [ ] means optional, and [[ ]] means optional, multiple times):

if ( condition1 ) {
      if-body-1
}
else if ( condition2 ) {
      if-body-2
}
[[ else if ( conditionN ) {
      if-body-N
} ]]
[else {
      else-body
} ]

where

  • condition1, condition2, etc. are boolean expressions;
  • if-body-1, if-body-2, etc. are blocks of zero or more statements;
  • else-body is a block of zero or more statements;
  • The if-else-if statement evaluates the condition expressions in the order given, executes the code in if-body of the first condition that evaluates to true, and skips the remaining else-if statements, as well as the else body.
  • If none of the condition expressions evaluate to true, the if-else statement executes the code in else-body, if present.

The following code prints the date, adding the appropriate “st”, “nd”, “rd”, or “th” suffix.

if (date == 1 || date == 21 || date == 31) {
   System.out.println(date + "st");
} 
else if (date == 2 || date == 22) {
   System.out.println(date + "nd");
} 
else if (date == 3 || date == 23) {
   System.out.println(date + "rd");
} 
else {
   System.out.println(date + "th");
}