Which of the following lines of code can individually replace the //INSERT CODE HERE line so that the code compiles successfully?
public class Main { public static int getVal() { return 100; } public static void main(String args[]) { int num = 10; final int num2 = 20; switch (num) { // INSERT CODE HERE break; default: System.out.println("default"); } } }
a, c, d
A is correct. Compile-time constants, including expressions, are permissible in the case labels.
B is incorrect. The case labels should be compile-time constants. A non-final variable isn't a compile-time constant because it can be reassigned a value during the course of a class's execution.
C is correct. The value specified in the case labels should be assignable to the variable used in the switch construct.
10/3 discards the decimal part and compares 3 with the variable num.
D is correct. The variable num2 is defined as a final variable and assigned a value on the same line of code, with its declaration. It's considered to be a compile-time constant.