How to use Switch Case Statements in Java

A switch-case statement in Java allows you to run different blocks of code depending on the value of a variable.

 

switch-case Syntax

Before we look at some examples, let's look at the syntax of a Java switch-case statement to understand how it works.

 

switch (variable)
{
   case value_1:
       //code to run
   case value_2:
       //code to run
   default:
       //default code to run
}

 

  • variable – the variable to evaluate. It can be an integer, string or enum.
  • case value_1 – if the variable is equal to value_1, execute the code in this block.
  • default (optional) – if no cases match the variable run the code in the default block.

 

switch-case Example

Here is an example of a Java switch-case statement used on an integer.

 

int day = 1;

switch (day)
{
   case 1:
       System.out.println('It is Monday!')
       break;
   case 2:
       System.out.println('It is Tuesday!')
       break;
   default:
       System.out.println('Invalid day!')
       break;
}
It is Monday!

 

Important behaviour to observe – duplicate case values are not allowed and cases after a true case will be checked if a break statement isn't used.