Switch Statement in Java | Use, Example

A switch statement in Java is a conditional control statement (or multiway decision statement) that executes one statement from multiple conditions.

It uses the result of an expression to evaluate which statements to execute. It is an alternative to if-else-if ladder statement.

In other words, a switch statement executes statements based on the value of a variable or an expression, against a list of case values.

If a match is found, a block of statements corresponding to that case is executed.

Syntax to Switch Statement in Java


The general syntax of the switch statement in Java is shown below:

switch(integer expression)
{
 case value-1:
  // statement sequence
      break;
 case value-2:
  // statement sequence
     break;
   . . . . . 
   . . . . .
 case value-n:
  // statement sequence
     break;
 default:
   // default statement sequence
}
statement-x;

a) In the switch syntax, an expression must be of data types byte, short, int, char, long, or String. From Java 7 onwards, we can use string in the switch statement.

We can also use four wrapper classes such as Byte, Short, Integer, and Long in the switch statement.

b) value-1, value-2, value-3 . . . . are constants or literals. These constants are called case labels (or case clauses). Each of the values specified in the case labels must be of a type compatible with the expression. Duplicate case values are not permitted.

Note: Case labels cannot be variables, float values, or boolean expressions. The case labels value-1, value-2, . . . should be distinct.

c) A switch can have multiple case clauses depending on requirements and must be unique within a switch statement. The case labels must end with a colon (:).


d) The statement sequence is a list of statements and may contain zero or more statements.

e) After each case, a break statement is necessary inside the switch block to come out switch block.

f) The default statement sequence is optional and is executed when none of the previous cases are matched.

How does switch statement work in Java?


The flowchart of java switch statement for the selection process is shown in the below figure.

Java switch statement flowchart diagram

Java switch statement works like this:

a) When the switch statement is executed, the value of the expression is successively compared with each case value like value-1, value2-, . . .

b) If a match is found, the statement sequence following that case label is executed.

c) If the value of expression does not equal to value-1, value-2, . . . . then none of the statement sequences will be executed.

d) In this case, the default clause is executed, and then default statements are executed. However, the default statement is optional. If no case is matched and no default is present, then no further execution takes place.

e) The break statement is used inside the switch block to terminate a statement sequence. It is optional. It immediately ends the switch
statement.

f) When a break statement is executed, the control of execution is moved to the next statement-x after the switch statement (skipping all the rest of case statements).

Example Program based on Switch Statement


1. Let’s take a simple example program based on switch statement where we will execute a particular task depending on city value. We will take a variable city, that is initialized to d.


Depending on the city value, Mumbai is displayed when the value is m; Dhanbad is displayed when the value is d; and so on. If city value is neither of the specified values: m, d, c, or r, then none of the statements will be executed. In this case, the default statement will be executed and it will display no city.

Look at the source code to understand better.

Program source code 1:

package javaProgram;
public class SwitchTest {
public static void main(String[] args) 
{
// Declaring a variable for switch expression.
     char city = 'd'; // Here, city is set to 'd'.
// Switch expression with char value.
    switch(city){
// Case statements.
    case 'm':
      System.out.println("Mumbai");	
      break;
    case 'd':
      System.out.println("Dhanbad");
      break;
    case 'c':
      System.out.println("Chennai");
      break;
    case 'r':
      System.out.println("Ranchi");
      break;

// Default case statement.
    default:
    System.out.println("No city");
  }
 }}
Output:
             Dhanbad

In this program, since the city value is set to d, it will display “Dhanbad” as output and then executes break statement which terminates the switch block.

Program source code 2:

package javaProgram;
public class SwitchTest2 {
public static void main(String[] args) 
{
for(int i = 0; i < 5; i++)
switch(i){
case 0:
  System.out.println("Zero");	
  break;
case 1:
  System.out.println("One");
   break;
case 2:
  System.out.println("Two");
   break;
case 3:
  System.out.println("Three");
    break;
default:
   System.out.println("i is greater than 3");
  }
 }
}
Output:
             Zero
             One
             Two
             Three
             i is greater than 3

2. Let’s understand an example program based on if and switch statements where we will take total marks of five subjects from students as input.

Then, we will calculate the percentage of total marks, and display Grade based on the percentage. Look at the following program source code to understand better.

Program source code 3:

package javaProgram;
import java.util.Scanner;
public class GradeApplication {
public static void main(String[] args) 
{
 int per = 0;	
// Create an object of Scanner class to take an input.
  Scanner sc = new Scanner(System.in);	
 
System.out.println("Enter your total marks of five subjects:");
int total  = sc.nextInt();

if(total <= 500){
 per = total/5;
 System.out.println("Your percentage: " +per);
} else{
  System.out.println("Invalid marks");	
 }
int i = per/10;
switch(i){
case 9:
  System.out.println("Grade A+");
  break;
case 8:
  System.out.println("Grade A");	
   break;
case 7:
   System.out.println("Grade B+");
   break;
case 6:
   System.out.println("Grade B");
   break;
case 5:
   System.out.println("Grade C");
   break;
case 4:
   System.out.println("Grade D");
    break;
case 3:
    System.out.println("Fail");	
    break;
 }
}}
Output:
            Enter your total marks of five subjects:
            450
            Your percentage: 90
            Grade A+

4. Let’s create a program where we will not use break statements. It means that it will execute all statements after the first match.

Program source code 4:

package javaProgram;
public class SwitchTest3 {
public static void main(String[] args) 
{
 int num  = 20;
 switch(num) {
// Case statement without break statements.
 case 10: System.out.println("Ten");
 case 20: System.out.println("Twenty");
 case 30: System.out.println("Thirty");
 case 40: System.out.println("Forty");
 default: System.out.println("Default statement");
 }
}}
Output:
             Twenty
             Thirty
             Forty
             Default statement

5. Let’s create a program where we will use strings in the switch expression. The case labels must be string literal. Look at the source code below.

Program source code 5: Switch statement with string.

package javaProgram;
public class SwitchStringTest {
public static void main(String[] args) 
{
// Declaring a variable of string type.
   String gameLevel = "Intermediate";	
   int level = 0;

// Using string in switch statement. 
    switch(gameLevel) {
// Using string literal in switch case.
    case "Beginner": level = 1;
      break;
    case "Intermediate": level = 2;
      break;
    case "Expert": level = 3; 
      break;
    default: level = 0;
      break;
 }
System.out.println("Your game level is : " +level); 
 }
}
Output:
             Your game level is : 2

Nested Switch Statements in Java


Like if statements, we can also nest switch statements. That is, a switch can also be a part of the statement sequence of an outer switch. It is called nested switch.

When a switch statement is placed within a case statement or default statement of another switch statement, it is called nested switch in Java.

The purpose of using nested switch statement in a program is to tell Java to make another decision after first decision.

Since a switch statement defines its own block, no conflicts occur between the case labels in the inner switch and those in the outer switch.

Consider the following example program to understand nested switch statement.

Program source code 6:

package javaProgram;
public class NestedSwitchEx {
public static void main(String[] args) 
{
// E - ECE, C - CS, I - Information Technology.
  char branch = 'E';
  int collegeYear = 3;
switch(branch) 
{
case 'E':
 switch(collegeYear) // Inner switch
 {
 case 3:
 System.out.println("Microcontroller, Power Electronics, Analog circuit, Digital circuit");
 break;
 }
 break;
case 'C':
  switch(collegeYear) // Inner switch.
  {
  case 3:
    System.out.println("Java, Python, Data structure");  
     break;
  }
 break; 
case 'I':  
switch(collegeYear){
 case 3:
  System.out.println("EDC, Java, Data structure, Microprocessor");	
  break;
 }
break;
default:
  System.out.println("Invalid selection");
   break;
  }
 }}
Output:
              Microcontroller, Power Electronics, Analog circuit, Digital circuit

As you can see in this program, we can nest a switch statement inside another switch statement in Java.

Program source code 7: Wrapper class in Switch statement

package javaProgram;
public class WrapperSwitchCaseEx {
public static void main(String[] args) 
{
Integer age = 18;
switch(age) {
case 16:
 System.out.println("You are not eligible for vote");	
 break;
case 18:
 System.out.println("You are eligible for vote");
 break;
default:
 System.out.println("Please, enter valid age");
}
 }
}
Output:
             You are eligible for vote

When to use Switch Statement in Java


A switch statement can be used to select one block out of multiple blocks of statement. That is, it can be used to execute one statement from multiple conditions. It is a better choice than Java if-else-if ladder.

When you need to execute one statement out of two alternatives, use if-else statement.


Hope that this tutorial has covered almost all the important points related to switch statement in Java with example programs. I hope that you will have understood the basics of switch statement and its uses in the program.
Thanks for reading!!!
Next ⇒ Java break statement

⇐ Prev Next ⇒