1. Not exactly. val1++ always returns
another object i.e. an object different from the one val1 is pointing to currently. It does not necessarily "create" another object because it may return an object from the cache of Integer objects. As per Section 5.1.7 of JLS:
If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.
Here is a simple test:
Code: Select all
Integer i = 1;
Integer j = 2;
Integer k = 1;
System.out.println(i==k); //will always print true
System.out.println(i==j); //will always print true but try with i and j beyond -128 to 127.
2. No, i++ doesn't mean new Integer(i.intValue() +1). It means - first do i.intValue() +1, now apply the boxing conversion on the value as per the rule given above. i.e. if the value is between -128 to 127, then use the cached object otherwise it is up to the JVM implementation.
3. Integer (and other primitive wrapper objects) are immutable. So they don't change at all. It is the reference that points to a different object. In the cache, there are individual Integer objects - one for each int from -128 to 127. Depending on which int value you are trying to box, you will get an Integer object corresponding to that value.