Help in understanding how are Wrapper classes immutable
Siphiwe Madi
Ranch Hand
Joined: Aug 16, 2007
Posts: 70
posted
0
Hi Ranchers,
I read on the Core Java Vol 1, that: Wrapper classes are immutable - you cannot change a wrapped value after the wrapper has been constructed.
I understood this piece of information to imply that once you construct a wrapped object holding a value of (e.g 3), then you cannot change that value to (e.g. 4).
code: ---- public static void main(String[] args) {
Integer i = 3; System.out.println("initial value: " + i); // line 1: prints 3
//change the wrapped value n++; System.out.println("final value: " + i); // line 2: prints 4 } ----
I expected that the output of line 2, would print 3 (as it is said that you cannot change that value of a wrapped object), but instead the output is 4.
Can anyone please help me understand?
Regards, Siphiwe Madi
Regards, Siphiwe Madi
[SCJP, SCWCD, __] Next ... scjwsd
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35252
7
posted
0
I assume you meant "i++", not "n++".
The value of the Integer object didn't change. A new object got created and assigned to the object reference named i. The value of the original object is still the same, although its value isn't accessible any longer. If you create a second reference to the object, you can check that its value didn't change. Try the following: