Java OCA OCP Practice Question 3110

Question

Consider the following program:

class MyClass<T> {
        private static int count = 0;
        public MyClass() {
               count++;//ww  w  . java2s  . c  o m
        }
        static int getCount() {
               return count;
        }
}

public class Main {
        public static void main(String []args) {
               MyClass<Double> doubleCounter = new MyClass<Double>();
               MyClass<Integer> intCounter = null;
               MyClass rawCounter = new MyClass();                     // RAW
               System.out.println("MyClass<Double> counter is "
                      + doubleCounter.getCount());
               System.out.println("MyClass<Integer> counter is " + intCounter.getCount());
               System.out.println("MyClass counter is " + rawCounter.getCount());
        }
}

Which one of the following describes the expected behavior of this program?

a) This program will result in a compiler error in the line marked with comment RAW.
b) When executed, this program will print
     MyClass<Double> counter is 1
     MyClass<Integer> counter is 0
     MyClass counter is 1/*from w  w  w.  ja  v  a  2s  .  co  m*/
c) When executed, this program will print
     MyClass<Double> counter is 1
     MyClass<Integer> counter is 1
     MyClass counter is 1

d) When executed, this program will print
     MyClass<Double> counter is 2
     MyClass<Integer> counter is 0
     MyClass counter is 2
e) When executed, this program will print
     MyClass<Double> counter is 2
     MyClass<Integer> counter is 2
     MyClass counter is 2


e)

Note

Count is a static variable, so it belongs to the class and not to an instance.

Each time constructor is invoked, count is incremented.

Since two instances are created, the count value is two.




PreviousNext

Related