OCA Java SE 8 Building Blocks - OCA Mock Question Building Block 2








Question

Given the following class, which of the following is true?

      1: public class Main { 
      2:   
      3:  public void myMethod(boolean checked) { 
      4: 
      5:     if (checked) { 
      6: 
      7:     } 
      8:     System.out.println(result); 
      9: 
     10:   } 
     11: } 

  1. If String result = "java2s.com"; is inserted on line 2, the code will compile.
  2. If String result = "java2s.com"; is inserted on line 4, the code will compile.
  3. If String result = "java2s.com"; is inserted on line 6, the code will compile.
  4. If String result = "java2s.com"; is inserted on line 9, the code will compile.
  5. None of the above changes will make the code compile.




Answer



A, B.

Note

A is correct. Adding the variable at line 2 makes result an instance variable. Since instance variables are in scope for the entire life of the object.

B is correct because adding the variable at line 4 makes result a local variable with a scope of the whole method.

C is incorrect. Adding the variable at line 6 makes result a local variable with a scope of lines 6-7. Since it is out of scope on line 8, the println does not compile.

Adding the variable at line 9 makes result a local variable with a scope of lines 9 and 10.

D is incorrect. Since line 8 is before the declaration, it does not compile.

E is incorrect since A and B make code to compile.