Given the following code, which of the optional lines of code can individually replace the //INSERT CODE HERE line so that the code compiles successfully?
public class Main { public static void main(String args[]) { int num = 10; final int num2 = 20; switch (num) { // INSERT CODE HERE break; default: System.out.println("default"); } //from www.j a v a2s.co m } }
a, c, d
Option (a) is correct.
Compile-time constants, including expressions, are permissible in the case labels.
Option (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.
Although the previous class doesn't assign a value to it, the compiler still treats it as a changeable variable.
Option (c) is correct.
The value specified in the case labels should be assignable to the variable used in the switch construct.
You may think that 10/3 will return a decimal number, which can't be assigned to the variable num, but this operation discards the decimal part and compares 3 with the variable num.
Option (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.
Hence, it's considered to be a compile-time constant.