• Articles

Switch Case in Java

Switch Case in Java

Discover the importance of the switch case statement in Java through this blog. In addition, let’s explore its syntax and usage, understand how it functions, and learn important rules. Understand advanced concepts like nested switch cases, variations in case labels, and using wrapper classes and enums, along with practical examples. Master this fundamental control flow tool and enhance your Java coding skills.

Table of Contents

Watch this Video on Java for beginners

What is a Switch Case in Java?

The switch case in the Java programming language serves as a tool to perform various actions according to different conditions. It acts as a decision-maker when you assess a variable against several values. Each value is termed a ‘case,’ and by using the switch statement, you can execute specific code blocks based on the variable’s value. It provides a structured way to handle multiple possible conditions without using nested if-else statements, improving code readability and maintainability.

Syntax and Usage of Switch Cases in Java

The switch case is used when you want to perform different actions based on the value of a variable. It is helpful when you have multiple conditions to check against that variable.

Syntax:  

switch (expression) {
    case value1:
        // Code to execute if variable equals value1
        break;
    case value2:
        // Code to execute if variable equals value2
        break;
    // More cases as needed
    default:
        // Code to execute if a variable does not match any case
}

Example:

public class intellipaat {
    public static void main(String[] args) {
        int vehicle_code = 2;
        String vehicle_type;
        switch (vehicle_code) {
            case 1:
                vehicle_type = "Car";
                break;
            case 2:
                vehicle_type = "Motorcycle";
                break;
            case 3:
                vehicle_type = "Truck";
                break;
            case 4:
                vehicle_type = "Bus";
                break;
            default:
                vehicle_type = "Unknown Vehicle";
        }
        System.out.println("The vehicle type is: " + vehicle_type);
    }
}

Output: 

Go for this in-depth job-oriented Java Training Course now and learn Java in detail!

How Does the Switch Statement Work?

The switch case executes specific code blocks based on matches on the basis of a given condition, providing an organized way to handle various scenarios. The statement breaks after finding a matching case that enhances the code readability and efficiency compared to multiple if-else conditions.

Here’s how the switch case works:

  • Evaluation: The switch statement evaluates an expression (or a variable) once. This expression must result in a primitive data type such as an integer, character, or enumeration.
  • Comparison: The value of the expression is compared against the values in each case. If a case value matches the evaluated expression, the corresponding block of code associated with that case is executed.
  • Execution: When a match is found, the code within that case block executes. If there is no match, the default block (if provided) executes.
  • Breaking Out: After executing a case block, the ‘break’ statement ends the switch, and the program continues executing the code following the switch statement. Without a ‘break,’ the switch will continue executing the code for subsequent cases until a ‘break’ is encountered or the switch ends.

Get 100% Hike!

Master Most in Demand Skills Now !

Some Important Rules for Switch Statements

You can avoid mistakes and write code that works smoothly if you know the important guidelines for switch statements. Let’s explore these rules to make use of switch cases in Java more accurately:

  • Each case in a switch statement should have a different value. You cannot repeat the same value in different cases.
  • The values in cases should match the data type of the variable used in the switch. They have got to be of the same kind for proper comparisons.
  • Case values need to be constants or specific values. You cannot use variables as case values.
  • Inside the switch, ‘break’ helps to stop the sequence of actions in a case. It is not always necessary, but if you skip the break statement, the code will move to the next case.
  • The ‘default’ statement is like a backup plan in case none of the cases match. It is not a must-have, and you can place it anywhere in the switch block. However, if it is not at the end, make sure to include a ‘break’ afterward to avoid executing the next cases.

Ace your interview preparation through Java Interview Questions and get yourself industry-ready.

Omitting the Break Statement

When a ‘break’ statement is omitted within a switch case in Java, the code will continue executing the subsequent cases until a ‘break’ is encountered or until the end of the switch block. This is known as “falling through” the cases.

Example:

public class Intellipaat {
    public static void main(String[] args) {
        int month = 8;
        String month_name;
        String month_type;
        switch (month) {
            case 1:
                month_name = "January";
                break;
            case 2:
                month_name = "February";
                break;
            case 3:
                month_name = "March";
                break;
            case 4:
                month_name = "April";
                break;
            case 5:
                month_name = "May";
                break;
            case 6:
                month_name = "June";
                break;
            case 7:
                month_name = "July";
                break;
            case 8:
                month_name = "August";
                break;
            case 9:
                month_name = "September";
                break;
            case 10:
                month_name = "October";
                break;
            case 11:
                month_name = "November";
                break;
            case 12:
                month_name = "December";
                break;
            default:
                month_name = "Invalid month";
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                month_type = "31 days";
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                month_type = "30 days";
                break;
            case 2:
                month_type = "28/29 days";
                break;
            default:
                month_type = "Invalid month type";
        }
        System.out.println(monthName + " has " + month_type);
    }
}

Output: 

Learn more about Java Certification from this insightful Java Certification blog! 

Examples of Switch Cases in Java

Switch cases in Java offer a solution for managing multiple conditions efficiently. Let’s find out how the switch case in Java works in practical examples that showcase how this control structure simplifies code organization, handles various scenarios, and enhances the functionality of Java programs.

Nested Switch Case

Nested switch cases in Java refer to using a switch statement within another switch statement. It involves having a switch statement (inner switch) within the code block of another switch statement (outer switch). It allows for a more detailed evaluation of multiple conditions. The inner switch statement’s cases are selected based on the outer switch’s condition, allowing for a hierarchical decision-making structure based on different levels of conditions.

Example: 

public class NestedSwitchExample {
    public static void main(String[] args) {
        int floor = 1;
        int room = 2;
        switch (floor) {
            case 1:
                switch (room) {
                    case 1:
                        System.out.println("You are on Floor 1, Room 1");
                        break;
                    case 2:
                        System.out.println("You are on Floor 1, Room 2");
                        break;
                    default:
                        System.out.println("Invalid Room on Floor 1");
                }
                break;
            case 2:
                switch (room) {
                    case 1:
                        System.out.println("You are on Floor 2, Room 1");
                        break;
                    case 2:
                        System.out.println("You are on Floor 2, Room 2");
                        break;
                    default:
                        System.out.println("Invalid Room on Floor 2");
                }
                break;
            default:
                System.out.println("Invalid Floor");
        }
    }
}

Output: 

Case Label Variations

The case label in Java switch statements requires a constant expression at compile-time, like integers, characters, or enumerated types. The switch argument can be a variable expression that allows dynamic values during runtime.

Example:

import java.io.*;
class caselabel {
    public static void main(String[] args) {
        int x = 2;
        int y = 1;
        switch (x + y) {
            case 1:
                System.out.println("Result is 1");
                break;
            case 2:
                System.out.println("Result is 2");
                break;
            case 3:
                System.out.println("Result is 3");
                break;
            default:
                System.out.println("Default result");
        }
    }
}

Output: 

Use of Wrapper Class in Switch Statement

In Java, wrapper classes like an integer or a character encapsulate primitive data types. These wrappers can be used in switch cases, but it is important to note that switch cases typically expect constant expressions known at compile time.

Example:

public class WrapperSwitchExample {
    public static void main(String[] args) {
        Integer number = 2;
        switch (number) {
            case 1:
                System.out.println("Number is 1");
                break;
            case 2:
                System.out.println("Number is 2");
                break;
            case 3:
                System.out.println("Number is 3");
                break;
            default:
                System.out.println("Number not found");
        }
    }
}

Output: 

Use of Enum in Switch Statement

Enums in switch statements are used to handle different cases based on enum constants. Enums help organize related constants into a group, allowing for clearer and more structured code.

Example:

enum PaymentMethod {
    card, cash, online, UPI
}
public class EnumSwitch {
    public static void main(String[] args) {
        PaymentMethod selectedMethod = PaymentMethod.UPI;
        switch (selectedMethod) {
            case card:
                System.out.println("Payment via Debit/Credit Card");
                break;
            case cash:
                System.out.println("Payment with Cash");
                break;
            case online:
                System.out.println("Payment via Online Transfer");
                break;
            case UPI:
                System.out.println("Payment using UPI");
                break;
            default:
                System.out.println("Invalid payment method");
        }
    }
}

Output:

Conclusion

Switch cases in Java provide a flexible way to execute specific code blocks based on varying conditions. They allow the organized handling of different scenarios, enhancing code readability and efficiency. By using enums or wrapper classes within switch statements, Java programmers can categorize and process different cases or values more effectively.

Do you have any queries? join our Java community to clear all your doubts

FAQs

What is the use of a switch case in Java?

The switch case in Java serves as a control structure to execute different blocks of code based on the value of a variable. It simplifies decision-making by allowing multiple checks against a single variable.

Can I use a float or a string in a switch case?

No, Java’s switch case works with integral types (byte, short, int, char) and enumerated types. It does not support float, double, or string types directly in case labels.

Is it mandatory to include a 'break' statement in every case?

Not always. Including ‘break’ in each case helps prevent fall-through, where the code continues executing subsequent cases. However, omitting ‘break’ leads to executing multiple cases until a ‘break’ is encountered.

Can I use a variable in a case label in Java's switch case?

No, Java requires constant values or literals in case labels. You cannot use variables as case values in switch statements.

What happens if there's no 'default' case in a switch statement?

If none of the cases match the variable’s value and there is no ‘default’ case, the switch statement does not execute any code. Having a ‘default’ case provides a fallback for unmatched values.

Course Schedule

Name Date Details
Python Course 27 Jul 2024(Sat-Sun) Weekend Batch
View Details
Python Course 03 Aug 2024(Sat-Sun) Weekend Batch
View Details
Python Course 10 Aug 2024(Sat-Sun) Weekend Batch
View Details