What are Switch Statements in Java?

What are Switch Statements in Java?

On May 19, 2024, Posted by , In Java, With Comments Off on What are Switch Statements in Java?

Table of Content

Definition of Switch Statements

Switch statements are a type of conditional statement used in programming to control the flow of execution based on the value of a variable. Unlike if-else statements that check conditions in a sequential manner, a switch statement directly jumps to the case that matches the value of the variable, making the code cleaner and often more efficient. It is particularly useful when you have multiple conditions to check against a single variable.

Enhance your Java skills with our experienced trainers who are ready to guide you into becoming a seasoned Java professional with our Java training. Dive into hands-on, real-time projects that prepare you for real-world programming challenges. Enroll for a free demo today and start your journey towards Java expertise!

Code Example

Below is a simple code example in Java that demonstrates how to use a switch statement. This example checks the value of the variable day and prints the corresponding name of the day of the week.

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3; // For example, 3 represents Wednesday
        String dayName;
        
        switch (day) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "Invalid day";
                break;
        }
        
        System.out.println("Day of the week: " + dayName);
    }
}

In this example, the switch statement checks the value of day, and the corresponding case block is executed. The break keyword is used to exit the switch block after a match is found, preventing the execution of subsequent cases.

Read more: Object-Oriented Programming Java

Considerations for Switch Statements in Salesforce

trigger CaseTrigger on Case (before update) {
    for (Case caseRecord : Trigger.new) {
        switch on caseRecord.Status {
            when 'New' {
                // Handle new case
                caseRecord.Priority = 'High';
            }
            when 'In Progress' {
                // Handle case in progress
                caseRecord.Priority = 'Medium';
            }
            when 'Closed' {
                // Handle closed case
                caseRecord.Priority = 'Low';
            }
            when else {
                // Handle other statuses
                caseRecord.Priority = 'Normal';
            }
        }
    }
}

This trigger uses a switch statement to set the priority based on the case status, making it easy to manage and update the logic for different case scenarios.

Enum Example

public enum Season { SPRING, SUMMER, AUTUMN, WINTER }

Season currentSeason = Season.SUMMER;
switch on currentSeason {
    when SPRING {
        System.out.println('It\'s spring');
    }
    when SUMMER {
        System.out.println('It\'s summer');
    }
    when AUTUMN {
        System.out.println('It\'s autumn');
    }
    when WINTER {
        System.out.println('It\'s winter');
    }
}

These examples show how to use switch statements for various data types in Apex, adapting the syntax for each specific scenario.

Read more: Java and Cloud Integration

Use of break in switch statements

In a switch statement, the break keyword is crucial to prevent fall-through, which occurs when control flows into the next case block unintentionally. Without break, once a match is found, execution continues through all subsequent cases, which can lead to unexpected results. Using break ensures that only the code for the matched case is executed and then exits the switch block. This makes the code more predictable and easier to manage.

Here’s an example of using break in a switch statement:

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3; // Represents Wednesday

        switch (day) {
            case 1:
                System.out.println("Monday");
                break; // Exit the switch block
            case 2:
                System.out.println("Tuesday");
                break; // Exit the switch block
            case 3:
                System.out.println("Wednesday");
                break; // Exit the switch block
            case 4:
                System.out.println("Thursday");
                break; // Exit the switch block
            case 5:
                System.out.println("Friday");
                break; // Exit the switch block
            case 6:
                System.out.println("Saturday");
                break; // Exit the switch block
            case 7:
                System.out.println("Sunday");
                break; // Exit the switch block
            default:
                System.out.println("Invalid day");
                break; // Exit the switch block
        }
    }
}

In this example, when day is 3, the output will be “Wednesday”, and the break statement ensures that no other case blocks are executed after the match is found.

Read more: My Encounter with Java Exception Handling

Data types

A switch statement in Java works with the following data types:

  1. byte: A primitive type representing 8-bit signed integers.
  2. short: A primitive type representing 16-bit signed integers.
  3. int: A primitive type representing 32-bit signed integers.
  4. char: A primitive type representing single 16-bit Unicode characters.
  5. enum: A special class type that represents a group of constants.
  6. String: A class type representing a sequence of characters (introduced in Java 7).

Here is an example of a switch statement using the String data type:

public class SwitchStringExample {
    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;
            case "Saturday":
                System.out.println("It's Saturday.");
                break;
            case "Sunday":
                System.out.println("It's Sunday.");
                break;
            default:
                System.out.println("Invalid day.");
                break;
        }
    }
}

In this example, the switch statement evaluates the day variable and matches it with one of the case labels. The break statement ensures that only the matched case is executed.

Read more: Java Control Statements

Compile-time constants

In Java, case values in a switch statement must be compile-time constants. This means that you cannot use variables or runtime values directly as case labels; they need to be constants known at compile time. To use a variable as a case value, you must mark it as final so that its value is constant and known at compile time.

Here’s an example illustrating this:

public class SwitchCompileTimeConstants {
    private static final String DOG = "Dog"; // Compile-time constant

    public static void main(String[] args) {
        String animal = "Dog";
        
        switch (animal) {
            case DOG:
                System.out.println("It's a dog.");
                break;
            // Uncommenting the following line would cause a compilation error
            // case dog: // Error: constant expression required
            //     System.out.println("It's a dog.");
            //     break;
            default:
                System.out.println("Unknown animal.");
                break;
        }
    }
}

Explanation:

  1. Compile-Time Constant: The DOG variable is declared as static final, making it a compile-time constant.
  2. Switch Case: The switch statement uses the DOG constant in the case label.
  3. Non-constant Variable: If we try to use a non-final variable (e.g., dog) as a case label, it will result in a compilation error.
  4. Default Case: The default case handles any values that do not match the specified cases.

Read more: Java Arrays

The New switch Expression

In JDK 13, the switch expression introduced in JDK 12 has been enhanced, offering a more concise and flexible way to handle switch statements. This feature allows switch statements to return values and simplifies the syntax by removing the need for explicit break statements. To use the new switch expression, you need to enable preview features by passing the --enable-preview flag to the compiler.

Here is a code example demonstrating the new switch expression:

public class SwitchExpressionDemo {
    public static void main(String[] args) {
        String day = "MONDAY";
        String typeOfDay = switch (day) {
            case "MONDAY", "FRIDAY", "SUNDAY" -> "Weekend";
            case "TUESDAY", "WEDNESDAY", "THURSDAY" -> "Weekday";
            default -> throw new IllegalArgumentException("Invalid day: " + day);
        };

        System.out.println("The type of the day is: " + typeOfDay);
    }
}

Explanation:

  1. Switch Expression: Uses the -> syntax to return a value based on the input day, making the code more readable and concise.
  2. Multiple Cases: Combines multiple case labels into a single case with a comma, simplifying the handling of similar cases.
  3. Default Case: Throws an exception for invalid input, demonstrating how to handle unexpected values.
  4. Preview Feature: To compile this code with JDK 13, use the --enable-preview flag to activate the preview features.
Comments are closed.