Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Java Switch in Java

Java Switch in Java

In Java, the switch statement is used to execute one of many code blocks based on the value of a given expression. It's an alternative to using multiple if-else statements when you need to check a variable against several different values.

Syntax of switch Statement:

switch (expression) {    case value1:        // code block to be executed if expression == value1        break;    case value2:        // code block to be executed if expression == value2        break;    case value3:        // code block to be executed if expression == value3        break;    // You can have any number of case statements.    default:        // code block to be executed if expression doesn't match any value}

Explanation:

  • expression: The value or expression you want to check.

  • case valueX:: Each case represents a possible value for the expression.

  • break;: The break statement is used to terminate the switch statement once a match is found and the corresponding code block is executed. Without break, the program will "fall through" and execute the code for the subsequent cases.

  • default:: This is optional. It defines a block of code that gets executed if no case matches the value of the expression.

Example: Basic switch Statement

Here’s an example using a switch statement to check for different days of the week:

public class SwitchExample {    public static void main(String[] args) {        int day = 3;  // Let's assume 1 = Monday, 2 = Tuesday, 3 = Wednesday, etc.        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");        }    }}

Output:

Wednesday

Important Notes:

  1. The break Statement:
    The break is crucial because without it, the program would continue executing the following case statements even if one of the cases matched, a behavior known as "fall through."

  2. default Case:

    • The default case is executed if none of the case labels match the expression. It’s optional, but it’s good practice to include it to handle unexpected values.

  3. Data Types for switch Expression:
    The expression in a switch statement can be one of the following data types:

    • byte, short, int, char

    • String (since Java 7)

    • enum (since Java 5)

Example: switch with Strings

Here’s an example of using a switch statement with String values:

public class SwitchStringExample {    public static void main(String[] args) {        String day = "Wednesday";        switch (day) {            case "Monday":                System.out.println("Start of the week!");                break;            case "Wednesday":                System.out.println("Midweek day");                break;            case "Friday":                System.out.println("End of the workweek");                break;            default:                System.out.println("Invalid day");        }    }}

Output:

Midweek day

Example: switch with enum

You can also use switch with enum values. Here’s an example:

public class SwitchEnumExample {    enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }    public static void main(String[] args) {        Day day = Day.WEDNESDAY;        switch (day) {            case MONDAY:                System.out.println("Start of the week!");                break;            case WEDNESDAY:                System.out.println("Midweek day");                break;            case FRIDAY:                System.out.println("End of the workweek");                break;            default:                System.out.println("Weekend!");        }    }}

Output:

Midweek day

Example: switch Without break (Fall-Through Behavior)

If you omit the break statement, the program will fall through and execute all subsequent case blocks, even if a match is found.

public class SwitchFallThroughExample {    public static void main(String[] args) {        int day = 3;        switch (day) {            case 1:                System.out.println("Monday");            case 2:                System.out.println("Tuesday");            case 3:                System.out.println("Wednesday");            case 4:                System.out.println("Thursday");            default:                System.out.println("Invalid day");        }    }}

Output:

WednesdayThursdayInvalid day

Java 12 switch Expression (Enhanced switch)

In Java 12, a new version of the switch statement was introduced, where you can return a value directly from each case.

public class SwitchExpressionExample {    public static void main(String[] args) {        int day = 3;        String dayName = switch (day) {            case 1 -> "Monday";            case 2 -> "Tuesday";            case 3 -> "Wednesday";            case 4 -> "Thursday";            case 5 -> "Friday";            case 6 -> "Saturday";            case 7 -> "Sunday";            default -> "Invalid day";        };        System.out.println(dayName);    }}

Output:

Wednesday

Key Takeaways:

  • switch is used when you need to check a variable against multiple possible values.

  • It works with int, char, String, and enum types.

  • The break statement is necessary to stop the execution of further case blocks.

  • Fall-through can be achieved by omitting the break statement.

  • Java 12 introduced the enhanced switch expression, allowing for more concise syntax and direct value returns.

Let me know if you need more details or examples!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql