OCA Java SE 8 Method - OCA Mock Question Method 27








Question

What is the result of the following?

     1:  public class MyValue { 
     2:    static String result = ""; 
     3:    { result += "CCC"; } 
     4:    static  
     5:    { result += "UUU"; } 
     6:    { result += "RRR"; } 
     7: } 

     1: public class Main { 
     2:   public static void main(String[] args) { 
     3:     System.out.print(MyValue.result + " "); 
     4:     System.out.print(MyValue.result + " "); 
     5:     new MyValue(); 
     6:     new MyValue(); 
     7:     System.out.print(MyValue.result + " "); 
     8:   } 
     9: } 
  1. CCCUUURRRUUURRR
  2. UUUCCCRRRCCCRRR
  3. UUU UUUCCCRRRCCCRRR
  4. UUU UUU CCCUUURRRCCCUUURRR
  5. UUU UUU UUUCCCRRRCCCRRR
  6. UUURRR UUURRR UUURRRCCC
  7. The code does not compile.




Answer



E.

Note

result is a static variable.

static initializer only runs once per class.

The first two

    System.out.print(MyValue.result + " ");
    System.out.print(MyValue.result + " ");

only call static initializer once.

new MyValue();
new MyValue();

calls the instance initializers twice and value is initialized in the order they appear in the file

class MyValue {
  static String result = "";
  {
    result += "CCC";
  }
  static {
    result += "UUU";
  }
  {
    result += "RRR";
  }
}

public class Main {
  public static void main(String[] args) {
    System.out.print(MyValue.result + " ");
    System.out.print(MyValue.result + " ");
    new MyValue();
    new MyValue();
    System.out.print(MyValue.result + " ");
  }
}