Java OCA OCP Practice Question 3080

Question

Consider the following program:

public class Main {
        public static void main(String []args) {
               Integer i = 10;
               Integer j = 11;
               Integer k = ++i;         // INCR
               System.out.println("k == j is " + (k == j));
               System.out.println("k.equals(j) is " + k.equals(j));
        }
}

Which one of the following options correctly describes the behavior of this program?

a) When executed, this program prints
     k == j is false/*w  w  w.j av  a  2 s .c  o m*/
     k.equals(j) is false
b) When executed, this program prints
     k == j is true
     k.equals(j) is false
c) When executed, this program prints
     k == j is false
     k.equals(j) is true
d) When executed, this program prints
     k == j is true
     k.equals(j) is true
e) When compiled, the program will result in a 
   compiler error in the line marked with the comment INCR.


d)

Note

The Integer objects are immutable objects.

If there is an Integer object for a value that already exists, then it does not create a new object again.

In other words, Java uses sharing of immutable Integer objects, so two Integer objects are equal if their values are equal (no matter if you use == operators to compare the references or use equals() method to compare the contents).




PreviousNext

Related