Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the Java Switch Statement?
2.1.
Switch Case Java Syntax
3.
Some Important Rules for Switch Statements
4.
How does the Switch Statement Work?
5.
Flowchart of Switch Statement
6.
Java Nested Switch Statement
7.
Java Switch Statement with String
8.
Java Enum in Switch Statement
9.
Java Wrapper in Switch Statement
10.
Use of Switch Case in Java
11.
Advantages of Java Switch over If-Else
12.
Frequently Asked Questions
12.1.
What is a switch case in Java?
12.2.
How to use switch and case in Java?
12.3.
What types are switch case in Java?
12.4.
What is case vs switch statement in Java?
13.
Conclusion
Last Updated: Mar 27, 2024
Easy

Java Switch Case

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Making decisions is a crucial part of programming. In Java, the switch statement is one of the ways to make decisions based on a specific value. 

The switch statement allows you to specify a variable or an expression to compare against multiple values and execute different blocks of code based on the value of the variable or expression. 

It's a simpler and more concise way to write conditional statements than using multiple if-else statements. The switch statement is used in many Java applications and is an essential concept for every Java programmer to understand.

Java switch case

In this article, we will look at Switch case java illustrated with examples. We will also look at nested switch statements. 

So, grab your seat and let us start. 

What is the Java Switch Statement?

The switch statement is used to execute different blocks of code based on the value of a single variable or expression. It is an alternative to using multiple if-else statements for testing the same variable or expression against different values. A multi-way branch in switch case enables the value of an expression or variable to alter the control flow of programme execution. The switch statement's expression is just once evaluated. The value of each case label is compared to the value of the expression. 

The corresponding piece of code is run if there is a match. To exit the switch statement, use the break statement. If the break statement is not used, the next case label will be run even if the expression's value does not match.

 

Example: 

Java switch case

The boy is allowed to eat: 

=> Pizza on Monday,

=> Sandwich on Tuesday, 

=> Brownie on Wednesday,

=> Ice Cream on Thursday! 

Hence, based on the day, we will assign the food to the boy. This can be easily solved with if-else statements, so why use switch statements

The answer is if-else statements are more flexible and can handle complex conditions and multiple conditions, whereas switch statements are more concise and easier to read for multiple cases with a single expression.

Let us discuss its syntax.

Switch Case Java Syntax

switch (expression) {
    case value1:
        // code to execute when expression = value1
        break;
    case value2:
        // code to execute when expression = value2
        break;
    ...
    default:
        // code to execute when expression doesn't match any of the cases
        break;
}


The meaning of all the parameters used in the above syntax are given below:

  • expression: The expression is the variable or expression whose value we want to test against different values. 
     
  • cases: Each case specifies a possible value of the expression, along with the code to execute if the expression equals that value. 
     
  • break: The break statement is used to exit the switch statement after the matching case is executed. 
     
  • default: The default case is optional and provides a fallback option if none of the other cases match.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Some Important Rules for Switch Statements

Here are some important rules for Java switch statements:

  • The switch statement's expression needs to be of a type that can be compared to integers. This comprises the class String, the enum types, and the primitive types byte, short, char, and int.
     
  • The case labels must be literals or constants of the same type as the switch statement's expression.
     
  • Although using the break statement to exit the switch statement once the desired case has been executed is optional, it is a recommended strategy. If the break statement is not used, the next case label will be executed even if the expression's value does not match.
     
  • The default case is not required. The switch statement will automatically go on to the following statement if neither the default case nor a case label that matches the value of the expression are present.

How does the Switch Statement Work?

When a switch statement is executed the expression is evaluated then compared to each of the case labels

  • If a matching case is found, then the corresponding code block is executed
     
  • If there is no matching case, then the code in the default block is executed (if it is defined)
     

The break statement is used to exit the switch block.

Flowchart of Switch Statement

Flowchart of Switch Statement

Java Nested Switch Statement

A nested switch case is a switch statement that is contained within another switch statement. 

In other words, it is a switch statement that is used as one of the statements inside another switch statement.

Nested Switch Case Syntax

The syntax for a nested switch case is very similar to that of a regular switch case, with the addition of an inner switch statement inside one of the case blocks of the outer switch statement.

switch (outer) {

  case outerCase1:
    // do something
    
    switch (inner) {
    
      case innerCase1:
        // do something
        break;
        
      case innerCase2:
        // do something
        break;
        
      default:
        // do something
        break;
        
    }
    // do something
    break;
    
  case outerCase2:
    // do something
    
  default:
    // do something
    break;
}


In this syntax, outer is the variable that is being evaluated in the outer switch statement, and outerCase1outerCase2, etc., are the different cases that the switch statement can match.

Inside one of the case blocks of the outer switch statement, there is an inner switch statement that evaluates the value of innerinnerCase1innerCase2, etc., are the different cases that the inner switch statement can match.

Each case block in both the outer and inner switch statements can contain statements to execute when that case is matched. Both switch statements end with a break statement to exit the switch block.

Let us take an example: 

In this example, we have an outer switch statement that evaluates the value of outerVar. If outerVar is equal to 2, then we have a nested switch statement that evaluates the value of innerVar.

Code in Java

public class NestedSwitchCaseExample {
  public static void main(String[] args) {
  
    int outerVar = 2;
    int innerVar = 1;
    
    switch (outerVar) {
      case 1:
        System.out.println("Outer-case 1");
        break;
      case 2:
        switch (innerVar) {
          case 1:
            System.out.println("Inner-case 1");
            break;
          case 2:
            System.out.println("Inner-case 2");
            break;
          default:
            System.out.println("Invalid inner case");
            break;
        }
        break;
      case 3:
        System.out.println("Outer-case 3");
        break;
      default:
        System.out.println("Invalid outer case");
        break;
    }
  }
}


Output

Inner-case 1


Explanation

If innerVar is equal to 1, then the inner switch statement matches the first case and prints "Inner case 1". 

Otherwise, if innerVar is equal to 2, the inner switch statement matches the second case and prints "Inner case 2". 

If innerVar is not 1 or 2, the inner switch statement matches the default case and prints "Invalid inner case".

If outerVar is not 2, the outer switch statement checks the other cases and prints out the corresponding messages.

Java Switch Statement with String

We can take different actions based on the values of strings by using the Java switch statement with a string. The following describes how to use a switch statement with strings:

public class StringSwitch{
   public static void main(String[] args) {
       String day = "Tuesday";
       switch (day) {
           case "Monday":
               System.out.println("It's Monday!");
               break;
           case "Tuesday":
               System.out.println("It's Tuesday!");
               break;
           case "Wednesday":
               System.out.println("It's Wednesday!");
               break;
           case "Thursday":
               System.out.println("It's Thursday!");
               break;
           case "Friday":
               System.out.println("It's Friday!");
               break;
           default:
               System.out.println("It's a weekend day or an invalid day.");
               break;
       }
   }
}

 

Output

It's Tuesday!

Java Enum in Switch Statement

When working with a set of fixed constant values in Java, we can utilise an enum type in a switch statement to produce simpler and maintainable code. An example of how to utilise an enum in a switch statement is given below:

// Define an enum for days of the week
enum Day {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class Main {
   public static void main(String[] args) {
       // Use the Day enum in a switch statement
       Day today = Day.SATURDAY;
       switch (today) {
           case SUNDAY:
               System.out.println("A relaxing Sunday.");
               break;
           case MONDAY:
               System.out.println("The start of the workweek.");
               break;
           case TUESDAY:
               System.out.println("It's Tuesday.");
               break;
           case WEDNESDAY:
               System.out.println("Today is Wednesday.");
               break;
           case THURSDAY:
               System.out.println("Today is Thursday.");
               break;
           case FRIDAY:
               System.out.println("It's finally Friday!");
               break;
           case SATURDAY:
               System.out.println("Today is a fun Saturday.");
               break;
           default:
               System.out.println("Invalid day.");
       }
   }
}

 

Output:

Today is a fun Saturday.

Java Wrapper in Switch Statement

Switch statements may be used with Java wrapper classes. Byte, Short, Character, and Integer are the respective wrapper classes for the primitive types Byte, Short, Character, and Integer. String serves as the String class's wrapper.

As an example, the switch statement in the following code, which makes use of the wrapper class Integer, is valid:

public class DayOfWeek {
   public static void main(String[] args) {
       int day = 3;
       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 day");
               break;
       }
   }
}

 

Output:

Wednesday

Use of Switch Case in Java

Cleaner Code: When compared to employing a number of nested if-else statements for various situations, they make the code more legible and maintainable.

Multiple Branching: Switch-case statements are used when a single variable or expression must be tested under several different situations.

Value-Based Branching: You can utilise Enums and integral types (int, char, byte, and short) as the controlling expression in a switch-case statement.

Effective: When dealing with a lot of conditions, switch-case statements are frequently more effective than utilising many if-else statements.

Advantages of Java Switch over If-Else

Below are some of the advantages of switch over if-else: 

Advantages of Switch over If-Else
  • Simplifies code - Using a switch statement can be simpler and more concise than using multiple if-else statements to test the same variable or expression against different values.
     
  • Readability - Switch statements are often easier to read and understand than multiple if-else statements, especially when testing for a large number of values.
     
  • Performance - The use of switch statements can often lead to faster execution times than equivalent if-else statements, especially when the number of values being tested is large.
     
  • Error-prone - Switch statements are less error-prone than using multiple if-else statements because each case must have a unique value, and the default case can catch any unexpected values.
     
  • Better control - Switch statements provide better control flow than if-else statements because the break statement is used to exit the switch statement after the matching case is executed.

Frequently Asked Questions

What is a switch case in Java?

A control flow structure known as a switch-case statement is used in Java to make decisions based on the value of an expression. Based on the expression's value, you can choose from a variety of code blocks to execute.

How to use switch and case in Java?

In Java, you must specify the expression to be evaluated within the switch statement in order to use a switch-case statement. Each case label reflects one of the expression's potential values. The matching code block is performed when an expression matches a case value.

What types are switch case in Java?

Integral types like int, char, byte, and short are acceptable choices for the controlling expression in a switch-case statement in Java. Enums can also be used in switch-case logic in Java, resulting in type-safe and readable code.

What is case vs switch statement in Java?

When evaluating an expression in Java, the switch statement is used to provide the expression, and the case labels specify the expression's potential values. The case labels are compared to the expression's value, and if a match is discovered, the relevant code block is run.

Conclusion

The switch case java statement is an important concept in Java programming that allows you to execute different blocks of code based on the value of a given expression or variable.

By using a switch statement, you can simplify your code, improve its readability, and optimize its performance. With the right implementation, the switch statement can help you write better and more efficient code in Java.

Also read - Jump statement in java

To know more about decision-making statements, refer to this article. 

Happy Learning!

Previous article
Decision Making in Java
Next article
Conditional Statements in Java (If-Else Statement)
Live masterclass