OCA Java SE 8 Mock Exam 2 - OCA Mock Question 23








Question

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"); 
        } 
    } 
} 
  1. case 10*3: System.out.println(2);
  2. case num: System.out.println(3);
  3. case 10/3: System.out.println(4);
  4. case num2: System.out.println(5);




Answer



a, c, d

Note

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.