Here is my understanding.
- Step 1:. When you say
Integer counter = 0; what you are actually doing, Integer counter = new Integer(0); Here you create an Integer object whose value is 0 and counter indicates this. Step 2: Integer test = counter;
Now test also refers to the same Integer object we created in step 1.
Step 3:. This is the hard part. When you do counter++; In its main method, Java Auto-Boxing and Auto-Unpack functions implement the below code for you.
counter = Integer.valueOf(counter.intValue() + 1);
As an Integer class, immutable in Java, when the value increases from 0 to 1, the valueOf() method creates a new Integer object and stores the new value 1 in it instead of changing the value of the old object (see below for the implementation of the Java method valueOf () ). When you reference a new object using counter , it unlinked the old Integer object , whose value is 0. But the reference variable test still contains the old Integer object . This is why test prints the old value.
Java method valueOf () from Integer library class
638 public static Integer More ...valueOf(int i) { 639 assert IntegerCache.high >= 127; 640 if (i >= IntegerCache.low && i <= IntegerCache.high) 641 return IntegerCache.cache[i + (-IntegerCache.low)]; 642 return new Integer(i);
See below for a detailed schematic explanation.
A solid line implies that the reference variable is still holding the object.
The dashed line means that the reference variable no longer holds the object.

source share