OCA Java SE 8 Method - OCA Mock Question Method 3








Question

Which code can be inserted to have the code print 2?

public class Main {
  private int myNumber;
  boolean call;

  public Main() {
    // LINE 1
    call = false;
    // LINE 2
  }

  public Main(int myNumber) {
    this.myNumber = myNumber;
  }

  public static void main(String[] args) {
    Main m = new Main();
    System.out.println(m.myNumber);
  }
}
  1. Replace line 1 with Main(2);
  2. Replace line 2 with Main(2);
  3. Replace line 1 with new Main(2);
  4. Replace line 2 with new Main(2);
  5. Replace line 1 with this(2);
  6. Replace line 2 with this(2);




Answer



E.

Note

A and B will not compile because constructors cannot be called without new.

C and D will compile but will create a new object rather than setting the fields in this one.

F will not compile since this() must be the first code line inside constructor.