Java - Switch statement

Java

Share

In this tutorial we will learn about switch case statement in Java programming language.

Switch case statements are similar to the if else statement that we discussed in the previous tutorial.

Switch case syntax

switch (expression) {
  case value_1:
    // block_1 code
    break;

  case value_2:
    // block_2 code
    break;

  default:
    // default code
}

We use the switch statement to tests the value or expression against a list of case values. If a match is found then the code of that case is executed. If no match is found and if the default block exists then, we execute the code of the default block.

The switch expression is an integer expression or characters.

The value_1, value_2, ... and so on are constants or expressions that evaluates to an integer contants. They are also called case labels.

Each block consists of one or more statements.

The default is an optional case.

break statement marks the end of a particular block and takes us out of the switch statement.

Example #1: Write a program in Java to print result using switch case

In the following example we will print the name of the number.

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

    switch(num) {
      case 1:
        System.out.println("It's one!");
        break;

      case 2:
        System.out.println("It's two!");
        break;

      case 3:
        System.out.println("It's three!");
        break;

      default:
        System.out.println("It's something else.");
    }

    System.out.println("End of program.");
  }
}

Output:

It's three!
End of program.

Note! The break statement in the default is optional.

Explanation

The value num is matched with case 1: and it fails so, we move to the next case case 2: which also fails so, we move to case 3: and it is a match.

Since case 3: is a match so, we execute its code and we get "It's three!" as output.

Then we encounter the break statement which takes us out of the switch.

And finally, after coming out of the switch statement we get the "End of program." output.

Share

Recently Updated