OCA Java SE 8 Method - OCA Mock Question Method 2








Question

What is the result of the following?

     1: public class Main { 
     2:   String value = "AAA"; 
     3:   { value += "BBB"; } 
     4:   { value += "CCC"; } 
     5:   public Main() { 
     6:     value += "XXX"; 
     7:   } 
     8:   public Main(String s) { 
     9:     value += s; 
     10:  } 
     11:  public static void main(String[] args) { 
     12:    Main m = new Main("QQQ"); 
     13:    m = new Main(); 
     14:    System.out.println(m.value); 
     15:  } 
     16: } 
  1. AAABBBCCCXXX
  2. AAABBBCCCQQQ
  3. AAABBBCCCXXXQQQ
  4. AAABBBCCCQQQXXX
  5. AAABBBCCCQQQAAABBBCCCBBB
  6. The code does not compile.
  7. An exception is thrown.




Answer



A.

Note

Java runs the declarations and instance initializers first they appear.

The constructors are called twice in the main method and the QQQ value is overwritten by the second call.

public class Main {
  String value = "AAA";
  {/*from w  ww .  j av a  2  s  .  c  o  m*/
    value += "BBB";
  }
  {
    value += "CCC";
  }

  public Main() {
    value += "XXX";
  }

  public Main(String s) {
    value += s;
  }

  public static void main(String[] args) {
    Main m = new Main("QQQ");
    m = new Main();
    System.out.println(m.value);
  }
}

The code above generates the following result.