Introduction to Java: Switch Statements

Introduction to Java: Switch Statements


Switch Statement is used when we want to check equality of a variable against number of values.

Type in the following in a file called SwitchCaseStatement.java :


public class SwitchCaseStatement {
    public static void main(String[] args) {
        int num = 5;

        switch (num) {
            case 1:
                System.out.println("The number is 1");
                break;
            case 2:
                System.out.println("The number is 2");
                break;
            case 3:
                System.out.println("The number is 3");
                break;
            case 4:
                System.out.println("The number is 4");
                break;
            case 5:
                System.out.println("The number is 5");
                break;
            default:
                System.out.println("Default case");
        }
    }
}

When the program reaches the break statement it terminates the switch and continues to the next line after the switch statement. The default case is used for when none of the cases is true and must appear at the end of the switch.

Compile and run the source code :


$ javac SwitchCaseStatement.java
$ java SwitchCaseStatement


Output:


The number is 5


String Switch
Create a new file called StringSwitchCaseStatement.java and add the following :


public class StringSwitchCaseStatement {
    public static void main(String[] args) {
        String name = "Hayri";

        switch (name) {
            case "Java":
                System.out.println("The name is Java");
                break;
            case "Stockholm":
                System.out.println("The name is Stockholm");
                break;
            case "Hayri":
                System.out.println("The name is Hayri");
                break;
            default:
                System.out.println("Don't know the name");
        }
    }
}


Output:


$ javac StringSwitchCaseStatement.java
$ java StringSwitchCaseStatement

The name is Hayri


We can also use char data in switch statements.
Type in the following in a file called CharSwitchCaseExample.java :


public class CharSwitchCaseExample {
    public static void main(String[] args) {
        char ch = 'h';

        switch (ch) {
            case 'b':
                System.out.println("Character is b");
                break;
            case 'c':
                System.out.println("Character is c");
                break;
            case 'h':
                System.out.println("Character is h");
                break;
            default:
                System.out.println("Don't know the character");
        }
    }
}


Output:


$ javac CharSwitchCaseExample.java
$ java CharSwitchCaseExample

Character is h


Share this: