Java - What is the output: switch on int value

Question

What is the output of the following code.

public class Main{

  public static void main(String[] args) {


    int swit = 3;

    switch(swit) {
      case 2:
        System.out.println(2);
      case 3:
        System.out.println(3);
      case 4:
        System.out.println(4);
      case 5:
        System.out.println(5);
        break;
      default:
        System.out.println("hi");
    }
  }
}


Click to view the answer

3
4
5

Demo

public class Main{

  public static void main(String[] args) {


    int swit = 3;

    switch(swit) {
      case 2:/*from  w  w  w.j av  a  2 s  .  c  o m*/
        System.out.println(2);
      case 3:
        System.out.println(3);
      case 4:
        System.out.println(4);
      case 5:
        System.out.println(5);
        break;
      default:
        System.out.println("hi");
    }
  }
}

Note

Add break statement to case statement to jump out of swtich statement.

Related Quiz