Selection Statements

Selection Statements with One Condition

Selection statements are also known as conditional statements because they are based on the evaluation (true or false) of a condition (question). In this first paragraph we will study selection statements with one condition.

Some examples of conditions (questions) are:

Examples:

Is your salary greater than $2000.00?
Is the temperature below 50 degrees Fahrenheit?
Are there less than 100 passengers on the flight?

When the condition is true then a certain sequence of statements will be executed. A negative answer (false) will result in other actions. 

Examples: 

If your salary is greater than $2000.00 then 
   the tax rate will be increased by 5 percent (condition is true)

If there are less than 100 passengers on the flight then 
   the ticket price will be $110 (condition is true) 
else 
   the ticket price will be $80 (condition is false)

The following animation shows the choice of a ticket price based on a flight with 74 passengers:

Selection statement

Java Selection Statement

A selection statement in Java can be programmed by means of the following if structure:

if (logical expression) {
   code to be executed;
}
else {
   code to be executed;
}

The else branch (false) is optional and can be omitted from the statement. Even the curly braces can be omitted when there is only one instruction in the true or false block.

Logical Expression

The logical expression makes use of relational operators between two operands (variables and/or literals ) to define the condition. The Java relational operators are summarised in the next table:

Relational OperatorDescription
<Less than
<=Les than or equal to
>Greater than
>=Greater than or equal to
==Equal to
!=Not equal to
Relational operators

In order to test the equality of two operands Java makes use of two equal signs (==). As you may remember from the previous chapter one equal sign (=) is used to assign a value to a variable.

The equality operator in Java is ==
The assignment operator in Java is =
Examples:

if (salary > 2000){
   taxRate = taxRate + 5.0;
}

if (numberPassengers < 100){
   ticketPrice = 110;
}
else{
   ticketPrice = 80;
}

The Java program to calculate the price of a ticket, based on the number of passengers on the flight, is shown below:

//Selection.java
//Carlos De Backer
public class Selection{
   public static void main (String[] args){
      int numberPassengers, ticketPrice;
      
      numberPassengers = 74;
      
      if (numberPassengers < 100) {
         ticketPrice = 110;
      }
      else {
         ticketPrice = 80;   
      }
      
      System.out.println ("Number Passengers: "+ numberPassengers);
      System.out.println ("Price ticket: "+ ticketPrice);
   }
}
Number Passengers: 74
Price ticket: 110

Two conditions can be combined by conditional operators to form one logical expression. The conditional operators are summarised in the next table:

Conditional OperatorDescription
&&AND operator (true when both conditions are true)
||OR operator (true if any of the given conditions is true)
!NOT (inverts the result of a logical expression) (This is an unary operator but can also be used to invert the result of a logical expression)
Conditional operators
Examples:

In the next examples conditional operators are used to determine the special ticket price for young people under 12 years ($10.00) and for elderly from 65 years ($10.00). The regular price for an entrance ticket is $15.00.

ticketPrice = 15.00;
if ((age < 12) || (age >= 65)){
   ticketPrice = 10.00;
}

ticketPrice = 10.00;
if (!((age < 12) || (age >= 65))){
   ticketPrice = 15.00;
}

Selection Statements with Multiple Conditions

Nested if Statements

Sometimes a programmer has to evaluate several conditions before a result can be found. The next program prints the name of the day corresponding with the number (variable number) of the day in the week (the program will be limited to 3 consecutive days):

//Selection1.Java - Multi selections
//Carlos De Backer
public class Selection1 {
   public static void main (String[] args){
      int number;
      
      number = 2;
      
      if (number == 1){
         System.out.println("Day: "+"Monday");
      }
      else if (number == 2){
         System.out.println("Day: "+"Tuesday");
      } 
      else if (number == 3){
         System.out.println("Day: "+"Wednesday");
      }   
      else {
         System.out.println("Name Unavailable");
      } 
   }
}

In the example an else branch is always associated with the last incomplete if sentence (in this case, the first else is associated with if (number == 1), the second else is associated with if (number == 2) and so on). The last else contains the code to be executed if all conditions are false.

Switch Statement

Another way to solve the above problem makes use of a switch statement. The switch statement has the following structure:

switch (expression){
   case literal1:
      code to be executed;
      break;
   case literal2:
      code to be executed;
      break;
   case literal3:
      code to be executed;
      break;
   ...
   default:
      code to be executed;
}

The Java program to show the name of the day can be developed as follows:

//Selection2
//Carlos De Backer
public class Selection2{
   public static void main(String[] args){
      int number;
   
       number = 4;
      
      switch (number){
      case 1:
         System.out.println("Day: "+"Monday");
         break;
      case 2:
         System.out.println("Day: "+"Tuesday");
         break;
      case 3:
         System.out.println("Day: "+"Wednesday");
         break;
      case 4:
         System.out.println("Day: "+"Thursday");
         break;
      case 5:
         System.out.println("Day: "+"Friday");
         break;
      case 6:
         System.out.println("Day: "+"Saturday");
         break;
      case 7:
         System.out.println("Day: "+"Sunday");
         break;
      default:
         System.out.println("Name Unavailable");
      }
   }
}
Day: Thursday

The expression of the switch statement must be of data type byte, short, int or char. The switch statement evaluates its expression and executes all statements following the matching case. The default branch is optional. 

Be careful not to forget the break statement at the end of each case. A break statement terminates the matching case and gives control to the statement following the switch block. If the break statement is omitted all the statements available in the consecutive cases will be executed.

Look what will happen when we omit the break lines:

//Selection3
//Carlos De Backer
public class Selection3{
   public static void main(String[] args){
      int number;
   
       number = 4;
      
      switch (number){
      case 1:
         System.out.println("Day: "+"Monday");
      case 2:
         System.out.println("Day: "+"Tuesday");
      case 3:
         System.out.println("Day: "+"Wednesday");
      case 4:
         System.out.println("Day: "+"Thursday");
      case 5:
         System.out.println("Day: "+"Friday");
      case 6:
         System.out.println("Day: "+"Saturday");
      case 7:
         System.out.println("Day: "+"Sunday");
      default:
         System.out.println("Name Unavailable");
      }
   }
}

And the ‘strange’ result will be:

Day: Thursday
Day: Friday
Day: Saturday
Day: Sunday
Name Unavailable
A break statement is necessary to end the execution of the matched case and to give control to the first statement following the switch block.