1

Code Snippet

public class WrapperClass {

    public static void main(String[] args) {
        Integer i1 = 400;
        Integer i2 = i1;
        i1++;
        System.out.println(i1 + "  " + i2);
    }
}

Output is 401 400 . I am not sure how wrapper objects work. Arent i1 and i2 pointing to same object ? What happens on java heap when the above code executes ?

Abhishek Singh
  • 10,243
  • 22
  • 74
  • 108

4 Answers4

3

The reason is simple, Wrapper classes are immutable. To explain in detail:-

Integer i1 = 400;
Integer i2 = i1;

Now i1 and i2 point to the same object.

with this i1++ , a new object (with value 401) is created and assigned to i1, while i2 still continues to point to the old object (with value 400).

Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
1

The output is correct. Reason behind this is Integer immutability.

G. Demecki
  • 10,145
  • 3
  • 58
  • 58
0

Yes, of course all wrapper classes are immutable.

Viswanath Donthi
  • 1,791
  • 1
  • 11
  • 12
0

It is not very hard to understand

i1++; 

means

i1 = new Integer(i1.intValue()+1);
Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
  • What's hard to understand is how you'd write your own wrapper class to do that. It's not like java lets you overload operators. – candied_orange Mar 26 '15 at 06:55