Java OCA OCP Practice Question 1832

Question

This question may be considered too advanced for this exam.

What will the following code print when run?

public class Main{
    public static Integer wiggler (Integer x){
       Integer y = x + 10;/*ww  w. j  a v  a2s. c om*/
       x++;
       System.out.println (x);
       return y;
     }

    public static void main (String [] args){
       Integer i = new Integer (5);
       Integer value = wiggler (i);
       System.out.println (i+value);
     }
}

Select 1 option

  • A. 5 and 20
  • B. 6 and 515
  • C. 6 and 20
  • D. 6 and 615
  • E. It will not compile.


Correct Option is  : C

Note

Wrapper objects are always immutable.

Therefore, when i is passed into wiggler () method, it is never changed even when x++; is executed.

However, x, which was pointing to the same object as i, is assigned a new Integer object (different from i) containing 6.

If both the operands of the + operator are numeric, it adds the two operands.

Here, the two operands are Integer 5 and Integer 15, so it unboxes them, adds them, and prints 20.




PreviousNext

Related