0
Are Wrapper objects really immutable?
It is said that wrapper objects in java are immutable. If yes , how can you change the value of i(a wrapper object) in the given code. https://code.sololearn.com/cD5370TamK2f/?ref=app
5 Réponses
+ 2
What's happening here at runtime is:
Integer i = new Integer(56);
System.out.println(++i);
When you type ++i , compiler internally does this:
int x = i.intValue();
++x;
i = new Integer(x);// so it never does change the wrapper object directly but only increment the int value of the wrapper and reassigns it to the wrapper.
+ 8
see this how to create our own immutable class like Integer,String etc
https://code.sololearn.com/cLYGoysYAEGw/?ref=app
+ 1
See if this helps-
https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
+ 1
Objects of wrapper class are immutable means state of object won't be changed however the reference that points to object can be reassigned.
for example following is valid:
Integer a=new Integer(5);
Integer b=new Integer(6);
a=b;
You can reassign the reference but it'll make original reference to point to new instance without changing state of previously pointed object.
given code :
Integer i=new Integer(56);
System.out.println(++i);
When ++ operate on i it creates new instance of Integer class with value i+1 and assigns back it to i . original instance remains unchanged.
0
🇮🇳Omkar🕉 👍
And Satyam Joshi That's what exactly is mentioned in the java documentation as well, I shared the link instead of typing it.