Hi every one,
"wrapper objects are immutable". This is what we learn in the theory. ok thats fine. but i am confuse with the concept of Autoboxing.
Integer i1=new Integer(10);
System.out.print(i1); // 20
If the wrapper objects are immutable how can we change the values of wrapper objects?????
Why it won't give compile error????
Please anybody help regarding this ..........
As a result of autoboxing, the statementis executed as
i1 = Integer.valueOf(20);
Returns a Integer instance representing the specified int value.
You're not changing the value of an Integer object, you're assigning a different object to be referenced by the variable.
I believe that the autoboxing here acts the same as when you assign a String to a new string literal: behind the scenes you are creating a new Integer object with your second line. In other words, I believe that this:
is really this:
[Edit: Too late! Beaten by Darryl despite his slow connection!]
i1 = new Integer(20);
you meant, if there are any changes(assignments, increment, decrement) to a wrapper object, it create new wrapper object with the new result and it change the same reference which was in the previous object to the new object??????
am i correct?????
Probably because of the automatic box-unbox feature of Java. Read the following ... it explains it a little:
The Numbers Classes (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
Edit: ooops... was a little slow in positng :-)