Java - What is the output: case value constant

Question

What is the output?

public class Main {
  public static void main(String[] args) {
    int num1 = 10;
    int num2 = 10;
    switch (num1) {
    case 20:
      System.out.println("num1 is 20");
    case num2: 
      System.out.println("num1 is 10");
    }

    System.out.println(num2);
  }
}


Click to view the answer

case num2: // A Compile-time error. num2 is a variable and cannot be used as a label

Note

The labels for each case in a switch statement must be a compile-time constant.

The value of the labels must be known at compile time.

Related Quiz