Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
if-else
conditions

How to use Switch Case statement in Java

Educative Answers Team

In Java, a switch statement is used to transfer control to a particular block of code, based on the value of the variable being tested.

Note: Switch statements are an efficient alternative for if-else statements.

How it works

The switch is passed a variable, the value of which is compared with each case value. If there is a match, the corresponding block of code is executed.

svg viewer

Syntax

The general syntax of the switch statement is as follows:

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

The variable passed to the switch can be of following types:

  • Integer
  • Strings
  • Enums

Example

Consider the following example to get a better idea of how the switch statement works.

If you want to write a piece of code which prints the weather forecast corresponding to the given input.

class HelloWorld {
    public static void main( String args[] ) {
      
      int weather = 2;
      //passing variable to the switch
      switch (weather) 
      {
          //comparing value of variable against each case
        case 0:
          System.out.println("It is Sunny today!");
          break;
        case 1:
          System.out.println("It is Raining today!");
          break;
        case 2:
          System.out.println("It is Cloudy today!");
          break;
        //optional
        default:
          System.out.println("Invalid Input!");
    }
    }
}

Note:

  • Duplicate case values are not allowed.

  • The value of a case must be the same data type as the variable in the switch.

  • Adding the default case is optional but handling unexpected input is considered a good programming practice.

If the break statement is not used, all cases after the correct case are executed.

Execute the following code to see what happens if we eliminate the break statement from each code block:

class HelloWorld {
    public static void main( String args[] ) {
      
      int weather = 0;
      //passing variable to the switch
      switch (weather) 
      {
          //comparing value of variable against each case
        case 0:
          System.out.println("It is Sunny today!");
        case 1:
          System.out.println("It is Raining today!");
        case 2:
          System.out.println("It is Cloudy today!");
        //optional
        default:
          System.out.println("Invalid Input!");
    }
    }
}

RELATED TAGS

java
if-else
conditions
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring