Java OCA OCP Practice Question 1952

Question

What will be the result of compiling and running the following program?.

public class Outer {
  private int innerCounter;

  class Inner {// w  w w.j ava 2 s.c om
    Inner() {innerCounter++;}
    public String toString() {
      return String.valueOf(innerCounter);
    }
  }

  private void multiply() {
    Inner inner = new Inner();
    this.new Inner();
    System.out.print(inner);
    inner = new Outer().new Inner();
    System.out.println(inner);
  }

  public static void main(String[] args) {
    new Outer().multiply();
  }
}

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) The program will compile but throw an exception when run.
  • (c) The program will compile and print 22, when run.
  • (d) The program will compile and print 11, when run.
  • (e) The program will compile and print 12, when run
  • (f) The program will compile and print 21, when run.


(f)

Note

The nested class Inner is a non-static member class, and can only be instantiated in the context of an outer instance of the class Outer.

Each Outer object has its own counter for the number of Inner objects associated with it.

The instance method multiply() creates three objects of the class Inner: two in the context of the current Outer instance, and one in the context of a new Outer object.

The counter value printed by the first print statement is returned by the second Inner object which is associated with the current Outer object.

And since the current Outer object has two Inner objects associated with it at this point, the value 2 of its counter is printed.

The counter value printed by the second print statement is returned by the third Inner object which is associated with the new Outer object created in the multiply() method.

And since the second Outer object has only one Inner object associated with it, the value 1 of its counter is printed.




PreviousNext

Related