top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Switch Case In Java

Introduction

Welcome to an exciting journey into the heart of Java programming - the switch case in Java. We know that complex ‘if-else’ chains can become daunting. Hence, we introduce you to the power and simplicity of the switch case mechanism. It is a tool that enhances readability and elegantly simplifies your coding tasks. This comprehensive tutorial is designed to ignite your enthusiasm and elevate your programming skills. 

Syntax of Switch Case in Java[1]

The general syntax for a switch case in Java is as follows:

switch (expression) {
    case value1:
        // Code to be executed if expression equals value1
        break;
    case value2:
        // Code to be executed if expression equals value2
        break;
    // ...
    default:
        // Code to be executed if expression doesn't match any case values
}

Here, the ‘expression’ is evaluated once and compared with the values of each ‘case.’ If a match is found, the corresponding code block is executed. The ‘default’ code block is executed if there's no match.

Here's an example with switch case Java 17.

String day = "Sunday";

switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        System.out.println("It's a weekday");
        break;
    case "Saturday":
    case "Sunday":
        System.out.println("It's a weekend");
        break;
    default:
        System.out.println("Invalid day");
}

Here, the switch expression is the ‘day’ string. The program compares ‘day’ with each case. If it is any of the weekdays, the program prints, "It's a weekday." If ‘day’ is "Saturday" or "Sunday," the program prints "It's a weekend." If ‘day’ doesn't match any case, the program prints "Invalid day."

Remember

The 'break' statement is used to terminate the execution of the currently running case in the switch block. If omitted, the switch case will continue (fall through) to the next case. The 'default' keyword denotes a block of code to be executed if no cases match the switch expression. It's not mandatory but recommended to handle unexpected cases.

Significance of Break & Default Statements

When discussing the Switch Case in Java, it's vital to underscore the significance of the ‘Break’ and ‘Default’ statements. The ‘Break’ plays a key role in the operation of a switch case mechanism. It terminates the switch statement and transfers the execution to the next sequence of code. Without a ‘Break’ statement, the program would continue executing the next case, leading to incorrect results and inefficiency, known as a fall-through.

The ‘Default’ statement is another vital component. It is executed when none of the cases match the switch expression, serving as a catch-all clause. This ensures that our switch case statement produces output even in scenarios where the switch expression doesn't match any predefined case.

When dealing with a switch case in Java string, the importance of ‘Break’ and ‘Default’ statements cannot be overstated.

Flow Diagram of Switch-Case Statement: A Visual Guide

A flow diagram can be a valuable tool to grasp Java's switch case concept fully. It visually breaks down the sequence of operations in a switch case statement, making it easier to understand the process.

First, picture a ‘start point,’ from which an arrow leads to a box. This box represents the switch expression evaluation – the heart of our switch case in Java 8. It determines which path our program takes next.

Follow this graphical representation for a better understanding:

Important Rules for Switch Statements in Java

  1. Switch Expression Data Type

The switch expression must be of byte, short, int, char, enum type, or String. It doesn't work with long, float, double, or boolean.

int month = 2;
switch (month) {
// case statements
}
  1. Unique Case Values

Each case value must be a unique literal or constant expression. Duplicate are not allowed.

char grade = 'B';
switch(grade) {
    case 'A':
        // code block
        break;
    case 'B':
        // code block
        break;
    default:
        // code block
}

In this Java code, the ‘switch’ statement evaluates ‘grade’ as 'B,' executing the corresponding ‘case 'B': code block then exits due to the ‘break’ statement.

  1. Break Statement

Although not mandatory, it's a good practice to include a break statement in each case to prevent fall-through, where control would continue on to the next case's code.

String day = "Monday";
switch(day) {
    case "Monday":
        // code block
        break;   // prevents fall-through
    default:
        // code block
}
  1. Default Case

The default case, while not required, is recommended. It catches any cases not specifically handled and prevents undefined behavior.

int num = 5;
switch(num) {
    case 1:
        // code block
        break;
    case 2:
        // code block
        break;
    default:
        // code block for all other values of num
}
  1. Order of Cases

The order of cases doesn't matter unless you intentionally want to use fall-through.

int number = 2;
switch(number) {
    case 3:
        // code block
        break;
    case 2:  // This will be executed regardless of its position
        // code block
        break;
    default:
        // code block
}

These rules ensure that your switch statement works correctly and efficiently. If you adhere to these, the switch case statement in Java can be a powerful tool for controlling program flow.

Switch Statement in Java with Strings

Before Java SE 7, switch statements could only handle primitive integer types (byte, short, char, int) and enums, but with its arrival, the ability to use String objects in switch statements was introduced. See it in the below example.

public class Main {
    public static void main(String[] args) {
        String dayOfWeek = "Tuesday";

        switch (dayOfWeek) {
            case "Monday":
                System.out.println("Start of the work week");
                break;
            case "Tuesday":
                System.out.println("Time for meetings");
                break;
            case "Wednesday":
                System.out.println("Midweek work");
                break;
            case "Thursday":
                System.out.println("Almost there");
                break;
            case "Friday":
                System.out.println("End of the work week");
                break;
            case "Saturday":
            case "Sunday":
                System.out.println("Weekend!");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}

Here, the switch statement checks the ‘dayOfWeek’ string and matches it with the case values. Each case checks if the‘dayOfWeek’ string equals a specific day string. When it finds a match, it executes the code in that case block. In this instance, since ‘dayOfWeek’ is "Tuesday", the console will print "Time for meetings".

Time for meetings
[Execution complete with exit code 0]

Remember

Switch statement comparisons are case-sensitive. The string "Monday" is not the same as "monday". Also, null values in the switch expression will throw a NullPointerException.

How Does the Switch Statement Work?

At its core, a switch statement is a multi-way branch statement. It provides an easier method of dispatching the execution to different parts of code based on the value of the expression.

public class Main {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}

In this example, the switch expression is ‘day.’ The switch statement evaluates this and tries to find a match among the available case values. If an equivalent is found, it executes the code associated with that case. It executes the code within the ‘default’ case if no match is found.

In our example, ‘day’ is 3, which corresponds to "Tuesday." Therefore, "Tuesday" is printed on the console.

Tuesday
[Execution complete with exit code 0]

When discussing Java switch multiple cases, you must note that a single block of code can be executed for multiple case values. This is done by stacking the case statements without a break statement between them.

public class Main {
    public static void main(String[] args) {
        int number = 2;

        switch (number) {
            case 1:
            case 2:
                System.out.println("Number is either 1 or 2");
                break;
            default:
                System.out.println("Number is not 1 or 2");
        }
    }
}

In this example, if ‘number’ is either 1 or 2, the program will print "Number is either 1 or 2". Here, the switch case handles multiple cases (1 and 2) with the same block of code, showing how you can use Java switch multiple cases to simplify your code.

Number is either 1 or 2
[Execution complete with exit code 0]

Exploring Nested Switch Case Statements in Java

Nested switch case statements occur when a switch statement is placed inside another switch statement. This nesting can be as deep as you want it to be.

public class Main {
    public static void main(String[] args) {
        int outer = 1;
        int inner = 2;

        switch(outer) {
            case 1:
                System.out.println("Outer switch: case 1");
                
                switch(inner) {
                    case 1:
                        System.out.println("Inner switch: case 1");
                        break;
                    case 2:
                        System.out.println("Inner switch: case 2");
                        break;
                    default:
                        System.out.println("Inner switch: No matching case found");
                }
                break;
            case 2:
                System.out.println("Outer switch: case 2");
                break;
            default:
                System.out.println("Outer switch: No matching case found");
        }
    }
}

In this example, there is an outer switch statement with two cases and an inner switch statement with two cases nested within the first case of the outer switch.

When ‘outer’ is 1, the first case of the outer switch statement is executed. Inside this case, the ‘inner’ switch statement is encountered, which tests ‘inner’. Since ‘inner’ is 2, the second case of the inner switch statement is executed, printing "Inner switch: case 2".

Outer switch: case 1
Outer switch: case 2
[Execution complete with exit code 0]

Java Program: Utilizing Wrapper Classes in Switch Statements

Although the switch statement in Java traditionally works with primitive data types (byte, short, char, int), their wrappers, and enumerated types and Strings, it's worth noting that wrapper classes can also be utilized in switch statements.

Wrapper classes provide a way to use primitive data types (int, char, etc.) as objects. The Java library includes an object wrapper class for each of the eight primitive data types.

Here's a simple example demonstrating the use of an Integer wrapper class in a switch statement:

public class Main {
    public static void main(String[] args) {
        Integer number = Integer.valueOf(3);

        switch (number) {
            case 1:
                System.out.println("You entered one");
                break;
            case 2:
                System.out.println("You entered two");
                break;
            case 3:
                System.out.println("You entered three");
                break;
            default:
                System.out.println("Invalid number entered");
        }
    }
}

This program creates an ‘Integer’ object, ‘number,’ and assigns it a value of 3. The switch statement evaluates this ‘Integer’ object. Since Java automatically unboxes the ‘Integer’ to an ‘int’ for the switch case evaluation, the case corresponding to 3 is matched, and "You entered three" is printed to the console.

You entered three
[Execution complete with exit code 0]

Using Scanner Class with Switch Case in Java

The ‘Scanner’ class in Java is a widely used tool for taking user input. When combined with a switch case statement, it offers a dynamic way to control the flow of your program based on user input. Here's a simple example to illustrate this:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a number between 1 and 3:");
        int number = scanner.nextInt();

        switch (number) {
            case 1:
                System.out.println("You entered one");
                break;
            case 2:
                System.out.println("You entered two");
                break;
            case 3:
                System.out.println("You entered three");
                break;
            default:
                System.out.println("Invalid number entered");
        }

        scanner.close();
    }
}

This Java program accepts an integer input from the user. If you pass 1, 2, or 3 to the main function through the console input, the program will print "You entered one," "You entered two," or "You entered three," respectively.

For example, if you run the program and input '1' when prompted, the output will be:

Enter a number between 1 and 3:
1
You entered one

If you input any number other than 1, 2, or 3, it will print "Invalid number entered." For instance, inputting '5' would result in the following:

Enter a number between 1 and 3
5
Invalid number entered

In the context of the switch case in Java using Scanner, we design a program that accepts user input to control its flow. We import the Scanner class and create a Scanner object to capture user input. The user is prompted to input a number between 1 and 3, which is read by the ‘nextInt()’ method and stored in a variable. This variable is then evaluated by a switch case statement, which prints a specific output based on the entered number. In the end, we close the Scanner object to avoid resource leaks.

Switch Case in Java:  Programs with User Input

An example of switch cases in Java programs with user input is detailed here.

Let's consider a simple program where the user inputs a number corresponding to a day of the week, and the program outputs the name of the day:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a number between 1 and 7 representing a day of the week:");
        int day = scanner.nextInt();


        switch (day) {
            case 1:
                System.out.println("You entered: Sunday");
                break;
            case 2:
                System.out.println("You entered: Monday");
                break;
            case 3:
                System.out.println("You entered: Tuesday");
                break;
            // ... Continue for the rest of the week
            default:
                System.out.println("Invalid number entered");
        }

        scanner.close();
    }
}

Here, a Scanner object captures user input, which is then evaluated by a switch case statement to determine the day of the week. The day's name is printed based on the user's input. If an invalid number is entered, a default message is displayed.

Switch Case Practice Questions in Java

To bolster your understanding of switch case statements, it's valuable to tackle some practice questions. Here are a few to get you started:

  1. Day of the Week

Write a Java program that asks the user to enter a number from 1 to 7, each representing a day of the week. 1 represents Sunday, 2 represents Monday, and so on. The program should then print out the name of the day. Use a switch case statement for this task.

  1. Grade Calculation

Create a program where the user inputs a letter grade (A, B, C, D, or F). The program should then output the corresponding qualitative description (e.g., 'A' for 'Excellent,' 'B' for 'Good,' etc.). Use a switch case statement to match the grade letters with their descriptions.

  1. Simple Calculator

Write a Java program that performs basic arithmetic operations. It should take two numbers and an operator (+, -, *, /) as input from the user and perform the appropriate calculation using a switch case statement.

Conclusion

The switch case statement in Java is a powerful control flow structure that increases readability and efficiency in certain situations. The switch case shows versatility with user input via the Scanner class or application in nested scenarios. Whether you're dealing with primitive types, wrapper classes, or strings, mastering this construct is a beneficial addition to your Java programming skill.

FAQs

  1. How can I use null in a switch case?

Null can’t be used in a switch case. If you try to use null, Java will show a NullPointerException.

  1. What happens if I forget to use a break statement in my switch case?

If you omit the break statement in a switch case, the "fall-through" behavior occurs. This means that if a case matches, the program will execute the matched one and all the cases after it encounters a break statement or reaches the end of the switch block. This can be leveraged intentionally in some situations, but generally, it's advisable to use break statements to avoid unintended outcomes.

  1. What are the limitations of the switch statement?

            The limitations of a switch statement are:

  • Logical operators cannot be used with the switch statement.

  • Switch case variables can only have int and char data types.

  • Float or no data type is not allowed      

Leave a Reply

Your email address will not be published. Required fields are marked *