Immutability of object wrappers - what the thing really means

Ok, so it's known, that object wrappers (e.g. Integer, Double etc.) are immutable. But what does it really mean?
 Say, we have something like that
i = 10;
i = 100;
The compiler gives no error. What's happening here is called autoboxing. So the compiler makes this:
i = Integer.valueOf(10);
i = Integer.valueOf(100);
But this does not put us closer to an answer - what is immutability in contents of object wrappers. Let's keep on experimenting, and write something like that:
Integer j = i;
i == j ? System.out.println("i == j") : System.out.println("i != j");
i = 20;
i == j ? System.out.println("i == j") : System.out.println("i != j");
It prints :
i = j

i != j

The answer is here: i and j are references to objects, so we can change them (by assigning them to another objects). But when we actually do reassign i to another object (in our case to Integer 20), than a new object is created, but the old one is kept untouched (and j is referencing the old one, which equals to 10). That's why i and j are not equal in the end.

0 comments:

Post a Comment