OCA Java SE 8 Method - OCA Mock Question Method 25








Question

Which of the following will compile when inserted in the following code?

     public class Main { 
       final String v1 = "1"; 
       static String v2 = "2"; 
       String v3 = "3"; 
       { 
         // 1 
       } 
       static { 
         // 2 
       } 
     } 
  1. v1 = "a"; for // 1
  2. v2 = "a"; for // 1
  3. v3 = "a"; for // 1
  4. v1 = "a"; for // 2
  5. v2 = "a"; for // 2
  6. v3 = "a"; for // 2




Answer



B, C, E.

Note

v1 is a final instance variable and can only be set once: in the variable declaration, an instance initializer, or a constructor.

A does not compile because the final variable was already set in the declaration. v2 is a static variable.

E is correct since instance initializers are able to access static variables.

B is correct since static initializers are able to access static variables.

v3 is an instance variable.

D and F do not compile since a static initializer does not have access to instance variables.