In this post, you will learn to:

  • Identify the need for decision-making statements and its types.
  • Explain various forms of the if statement.
  • Explain the switch-case statement.
  • Compare the if-else and the switch-case construct.

Purpose and Types

A Java program is a set of statements, which are executed sequentially in the order in which they appear. However, in some cases, the order of execution of statements may change based on the evaluation of certain conditions.

The Java programming language possesses decision-making capabilities. The decision-making or control statements supported by Java are as follows:

  • if statement
  • if-else-if statement
  • switch-case statement

Decision-making statements enable us to change the flow of the program. Based on the evaluation of a condition, a statement or a sequence of statements is executed.

‘if’ Statement

The if statement can be implemented in various forms based on the complexity of the conditions to be tested. The different forms of the if statement are as follows:

Simple if statement

The if statement helps in decision-making based on the evaluation of a given condition to true or false. If the condition is true, then the statements in the if block get executed. If condition evaluates to false, the control is transferred directly outside the if block.

The following is the syntax of if statement.
Syntax:

if (condition)
{
    // one or more statements
}

The following code demonstrates the use of if statement.

Code Snippet:

int first = 400, second = 700, result;
result = first + second;
if(result > 1000)
{
       second = second + 100;
}
System.out.println("The value of second is " + second);

The program tests the value of result and accordingly calculates the value of second and prints it.If the result is greater than 1000, then the variable second gets increased by 100 and is printed. If not, the value of second is not increased and the original value is printed.

Output:

The value of second is 800

if-else statement

Generally, it is not only important to specify an action to be performed when the condition is true but also to specify what action is to be performed if the condition is false. To do this, the if-else statement can be used.

The following is the syntax of if-else statement.

Syntax:

if (condition)
{
    // one or more statements
}
else
{
    // one or more statements
}

The following code demonstrates the use of if-else statement.

Code Snippet:

int number = 11, remainder;
remainder = number % 2;
if(remainder == 0)
{
     System.out.println("Number is even");
}
else
{
     System.out.println("Number is odd");
}

The program checks whether a number is even or odd. If the remainder is 0, the message ‘Number is even’ is printed. Else, the message ‘Number is odd’ is printed.

Output:

Nested-if Statement

The if-else statement tests the result of a condition, that is, a boolean expression, and performs appropriate actions based on the result. An if statement can also be used inside another if. This is known as nested-if. Thus, a nested-if is an if statement that is the target of another if or else.

The important points to remember in nested-if statements are as follows:

  • An else statement should always refer to the nearest if statement.
  • It should be within the same block as the else and it should not be associated with an else.

The following is the syntax of nested-if statement.

Syntax:

if(condition) {
    if(condition)
        True-block statement(s);
   else
        False-block statement(s);

} else {
        False-block statement(s);
}

The following code demonstrates the use of nested-if statements.

Code Snippet:

Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
num = input.nextInt();

// Number is divisible by 3
//Outer if statement
if(num % 3 == 0) {
  
   //Number is divisible by 5
   // Inner if statement
   if (num % 5 == 0)
      
       //Message is displayed if number is divisible by both 3 and 5
       System.out.println("The number is divisible by both 3 and 5.");
   else
 
       //Message is displayed if number is divisible by 3 but not by 5
       System.out.println("The number is divisible by 3 but not by 5.");
     } else {
 
       //Message is displayed if number is not divisible by 3 and 5
       System.out.println("The number is not divisible by 3 and 5.");

Here, code declares a variable num and stores an integer value accepted from the user. Then, using nested-if statements, it checks whether num is divisible by 3 and 5 or only by 3, and then prints an appropriate statement. Here, the final else is associated with if(num % 3 == 0). The inner else refers to if(num % 5 == 0), because it is closest to the inner if within the same block.

Multiple if statements

The multiple if construct is known as the if-else-if ladder. The conditions are evaluated sequentially starting from the top of the ladder and moving downwards. When a true condition is found, the statement associated with the true condition is executed.

The following is the syntax of if-else-if construct.

Syntax:

if(condition)
{
    // one or more statements
}
else if (condition)
{
    // one or more statements
}
else
{
    // one or more statements
}

The following code demonstrates the use of if-else-if construct.

Code Snippet:

int totalMarks = 59;
if(totalMarks >= 90)
{
   System.out.println("Grade = A+");
}
else if (totalMarks >= 60)
{
   System.out.println("Grade = A");
}
else if (totalMarks >= 40)
{
   System.out.println("Grade = B+");
}
else if (totalMarks >= 30)
   System.out.println("Grade = B");
}
else
{
   System.out.println("Fail");
}

Output:

‘switch-case’ Statement

A program is difficult to comprehend, when there are too many if statements representing multiple selection constructs. To avoid this, the switch-case approach can be used as an alternative for multiple selections. The use of the switch-case statement results in better performance.

The switch-case statement is used when a variable needs to be compared against different values. The figure below shows the syntax of switch-case statement.

FIGURE

switch

The switch keyword is followed by an integer expression enclosed in parentheses. The expression must be of type int, char, byte, or short. Each case value must be a unique literal. Thus, it must be a constant and not a variable. The switch statement executes the case corresponding to the value of the expression. The break statement terminates the statement sequence and continues with the statement following the switch. If there is no corresponding case value, the default clause is executed.

case

The case keyword is followed by an integer constant and a colon. Each case value is a unique literal. The case statement might be followed by a code sequence that are executed when the switch expression and the case value match.

default

If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the “else” for the switch statement.

break

The break statement is used inside the switch-case statement to terminate the execution of the statement sequence. The control is then transferred to the first statement after the end of the switch. The break statement is optional. If there is no break, execution flows sequentially into the next case statement. Sometimes, multiple cases can be present without break statements between them.

The following code demonstrates the use of switch-case statement.

Code Snippet:

int choice = 3;
switch (choice)
{
   case 1:
      System.out.println("Addition");
      break;
  case 2:
      System.out.println("Multiplication");
      break;
  case 3:
      System.out.println("Division");
      break;
  case 4:
      System.out.println("Subtraction");
      break;
 default:
     System.out.println("Invalid choice");
}

Output:

In the code, case 3 will be executed because value of choice is 3. So, the message, Division is displayed, and in the next statement when break is encountered the program exits.

Nested-switch-case Statement

A switch statement can also be used as part of another switch statement. This is called a nested switch. Since, a switch-case statement defines its own blocks, no conflicts arise between the case constants in the inner switch and those in the outer switch. The following code demonstrates the use of nested-switch-case statements.

Code Snippet:

.....
switch(day) {
    case 0:
        switch(target) {
           case 1:
             System.out.println("Target is 1 to 7.");
           break;
          }
       break;
    case 1:
      System.out.println("Sunday");
       break;
    case 2:
      System.out.println("Monday");
       break;
    case 3:
      System.out.println("Tuesday");
       break;
    case 4:
      System.out.println("Wednesday");
      break;
.....

As shown in the code, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The variable day is only compared with the list of cases at the outer level. If day is 0, then target is compared with the inner list cases.

There are three important features of switch statements and they are as follows:

  • The switch differs from if. The switch can only test for equality, whereas if can test for any type of Boolean expression. The switch looks only for a match between the value of the expression and one of its case constants.
  • No two case constants in the same switch can have identical values, but a switch statement enclosed by an outer switch can have case constants in common.
  • A switch statement is more efficient than a set of nested-if statements.

if-else-if and switch-case Comparison

The if-else-if and the switch-case decision-making statements have similar use in a program, but there are distinct differences between them.

The table below lists the differences of if and switch statement.

if-else-if switch
Each if has its own logical expression to be evaluated as true or false. Each case refers back to the original value of the expression in the switch statement.
The variables in the expression may evaluate to a value of any type. The expression must evaluate to a byte, short, char or int.
Only one of the blocks of code is executed. If the break statement is omitted, the execution will continue into the next block.