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

8th Jan 2020, 4:36 PM
Satyam Joshi
Satyam Joshi - avatar
5 ответов
+ 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.
8th Jan 2020, 5:18 PM
Satyam Joshi
Satyam Joshi - avatar
+ 8
see this how to create our own immutable class like Integer,String etc https://code.sololearn.com/cLYGoysYAEGw/?ref=app
9th Jan 2020, 6:12 PM
Saroj Patel
Saroj Patel - avatar
8th Jan 2020, 4:59 PM
Avinesh
Avinesh - avatar
+ 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.
8th Jan 2020, 5:15 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
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.
8th Jan 2020, 5:20 PM
Avinesh
Avinesh - avatar