Java Switch Statement – Learn its Working with Coding Examples

We all use electrical switches in our regular lives to control the electrical equipment. For each particular electrical equipment, there is a unique switch to operate them. And, each switch can activate or deactivate only one item.

Similarly, switches in Java are like these electrical switches only. Have you ever wondered how switch statement in Java helps us in decision-making?

The answer is switch statements help us with decision making in Java. They are useful to execute one statement from multiple conditions or expressions.

In this article, we are going to purely discuss and implement the switch case or switch statement in Java with examples.

Switch Statement in Java

A Java switch statement is a multiple-branch statement that executes one statement from multiple conditions. The switch statement successively checks the value of an expression with a list of integer (int, byte, short, long), character (char) constants, String (Since Java 7), or enum types.

It also works with some Java Wrapper Classes like Byte, Short, Integer, and Long. When it finds a match, the statements associated with that test expression are executed.

A Switch statement is like an if-else-if statement of Java. In other words, the switch statement checks the equality of a variable against multiple values.

The syntax or general form of a switch statement is:

switch (expression)
{
     case value1:
     statement1;
     break;

     case value2:
     statement2;
     break;
     .
     .
     case valueN:
     statementN;
     break;

     default:
     statementDefault;
}

Working of a Switch Statement

The switch statement evaluates the conditional expression and matches the values against the constant values specified in the case statements.

When it finds a match, the statement associated with that case is executed until it encounters a break statement. When there is no match, the default statement gets executed.

If there is no break statement, the control flow moves to the next case below the matching case and this is called the fall-through.

Some Important points about Switch Statements in Java

These are some important rules of the Java switch case:

  • There is no limit for the number of cases in a switch statement. There can be one or ‘N’ number of cases in a switch statement.
  • The case values should be unique and can’t be duplicated. If there is a duplicate value, then it is a compilation error.
  • The data type of the values for a case must be the same as the data type of the variable in the switch test expression.
  • The values for a case must be constant or literal types. The values can be int, byte, short, int, long or char.
  • We can also wrapper classes as the values of the cases that is, Integer, Long, Short, and Byte. Also, we can use the Strings and enums for the value of case statements.
  • We use the break statement inside the switch case to end a statement.
  • The break statement is optional, and in the absence of the break statement, the condition will continue to the next case.
  • The default statement in the switch case is also not mandatory, but if there is no expression matching the case (or if all the matches fail), then nothing will execute. There is no need for a break statement in the default case.
  • We can not use variables in a switch statement.

Examples of Switch Statement in Java

package com.techvidvan.switchstatement;
//A Java program to demonstrate the use of switch case
public class SwitchCaseDemo1
{
  public static void main(String[] args)
  {
    int day = 5;
    switch (day) {
    case 1:
      System.out.println("Monday");
      break;
    case 2:
      System.out.println("Tuesday");
      break;
    case 3:
      System.out.println("Wednesday");
      break;
    case 4:
      System.out.println("Thursday");
      break;
    case 5:
      System.out.println("Friday");
      break;
    case 6:
      System.out.println("Saturday");
      break;
    case 7:
      System.out.println("Sunday");
      break;
    default:
      System.out.println("Invalid");

    }
  }
}

Output:

Friday

Skipping the break statement in Java Switch: Fall-Through

The break statement is optional in the switch case. But, the program will still continue to execute if we don’t use any break statement. You can consider the below code for the same.

package com.techvidvan.switchstatement;
public class SwitchCaseDemo2
{
  //Switch case example in Java where we are omitting the break statement
  public static void main(String[] args)
  {
    int number = 20;
    //switch expression with integer value
    switch(number)
    {
    //switch cases without break statements
    case 10:
      System.out.println("Ten");
    case 20:
      System.out.println("Twenty");
    case 30:
      System.out.println("Thirty");
    default:
      System.out.println("Not in 10, 20 or 30");
    }
  }
}

Output:

Twenty
Thirty
Not in 10, 20 or 30

Multiple Case Statements for the same Operation

If there are multiple cases in the switch statement and you don’t want to write any operation in a case statement, then the control moves to the next case until it encounters the break statement. For example:

package com.techvidvan.switchstatement;
public class Test
{
  public static void main(String args[])
  {
    int number = 10;
    switch(number)
    {
    case 5 :
      //writing no operations for case 5

    case 10 : System.out.println("The number is " +number);
    break;
    default: System.out.println("The number is not 10");
    }
  }
}

Output:

The number is 10

yield Instruction in Java Switch Statement

We can use the Java switch yield instruction from Java 13. It returns a value from a Java switch expression.

Code to understand yield in Java switch:

package com.techvidvan.switchstatement;
public class YieldInstruction
{
  public static void main(String args[ ])
  {
    String token = "TechVidvan";
    int tokenType = switch(token)
    {
    case "TechVidvan": yield 0 ;
    case "Java": yield 1 ;
    default: yield -1 ;
    };
    System.out.println(tokenType);
  }
}

Output:

Value of tokenType is: 0

Nested Switch Statements in Java

When a switch statement has another switch statement inside it, it is called a nested switch statement. Let’s see an example to understand the nested switch statements in Java.

package com.techvidvan.switchstatement;
public class NestedSwitchCaseDemo
{
  //Java Switch Example where we are skipping the break statement
  public static void main(String args[ ])
  {
    String branch="CSE";		//Declaring string
    int year=2;		       //Declaring integer

    //switch expression
    //Outer Switch
    switch(year)
    {
    //case statement
    case 1:
      System.out.println("Optional courses for first year: Engineering Drawing, Learning C");
      break;

    case 2:
    {
      //Inner switch
      switch(branch)
      {
      case "CSE":
        System.out.println("Optional Courses for second year CSE branch: Cyber Security, Big Data and Hadoop");
        break;
      case "CCE":
        System.out.println("Optional Courses for second year CCE branch: Machine Learning, Big Data and Hadoop");
        break;
      case "IT":
        System.out.println("Optional Courses for second year IT branch: Cloud Computing, Artificial Intelligence");
        break;
      default:
        System.out.println("Optional Courses: Optimization");
      }
    }
    }
  }
}

Output:

Optional Courses for second year CSE branch: Cyber Security, Big Data and Hadoop

Using Strings with Java Switch Statement

Since Java SE 7, we can use the strings in a switch expression. The case statement should be a string literal.

Code to understand the switch case with String:

package com.techvidvan.switchstatement;
public class SwitchStringExample
{
  public static void main(String[ ] args)
  {
    //Declaring a String variable
    String operation = "Addition";

    int result = 0;
    int number1 = 20, number2 = 10;

    //Using String in switch expression
    switch(operation)
    {
    //Using String Literal in switch case
    case "Addition":
      result = number1 + number2;
      break;
    case "Subtraction":
      result = number1 - number2;
      break;
    case "Multiplication":
      result = number1 * number2;
      break;
    default:
      result = 0;
      break;
    }
    System.out.println("The result is: " +result);
  }
}

Output:

The result is: 30

Using Character Literals with Java Switch Statement

We can use the data type ‘char’ with the switch statement. The following code explains the switch statement using the character literal.

Code to understand the switch case with Character Literals:

package com.techvidvan.switchstatement;
public class SwitchCharExample
{
  public static void main(String[] args)
  {
    //Declaring char variable
    char courseId = 'C';

    //Using char in switch expression
    switch(courseId)
    {
    //Using Character Literal in the switch case
    case 'A':
      System.out.println("Techvidvan's Python Course");
      break;
    case 'B':
      System.out.println("Techvidvan's Big Data and Hadoop Course");
      break;
    case 'C':
      System.out.println("Techvidvan's Java Course");
      break;
    default:
      System.out.println("Invalid course id");
    }
  }
}

Output:

Techvidvan’s Java Course

Using Enum with Java Switch Statement

It is also possible to use Java enums with a switch statement. Below is a Java example that creates a Java enum and then uses it in a switch statement.

Code to understand the switch case with the Java enums:

package com.techvidvan.switchstatement;
public class SwitchOnEnum
{
  private static enum Size
  {
    SMALL, MEDIUM, LARGE, X_LARGE
  }
  void switchOnEnum(Size size)
  {
    switch(size)
    {

    case SMALL:
      System.out.println("Size is small");
      break;
    case MEDIUM:
      System.out.println("Size is medium");
      break;
    case LARGE:
      System.out.println("Size is large");
      break;
    case X_LARGE:
      System.out.println("Size is X-large");
      break;
    default:
      System.out.println(Size is not S, M, L, or XL”);
    }
  }
  public static void main(String args[])
  {
    SwitchOnEnum obj = new SwitchOnEnum();
    obj.switchOnEnum(Size.LARGE);
  }
}

Output:

Size is large

Use Cases of Java Switch Statement

  • The Java switch expressions are useful where you have multiple choices, cases, or options and you need to test these values against a single value.
  • Switch statements are mainly useful when we want to resolve one value to another. For example, when we need to convert the weekday (number) to a weekday (String), or vice versa.
  • Switch expressions in Java are also useful in parsing String tokens into integer token types or, character types into numbers.

Summary

With this, we have come to an end of this tutorial on switch case statement in Java. And now you are well familiar with the switch statement in Java. We learned to implement it in many different scenarios according to our needs.

A switch statement can help you with better decision making in Java. They are also very useful for parsing one type of value to the other. As a Java beginner, you should master this concept to become an expert in Java programming.

Thank you for reading our article. Do share our article on Social Media.

Happy Learning 🙂