• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wrapper classes are immutable  RSS feed

 
Duc Ta
Ranch Hand
Posts: 46
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys,
I have known that wrapper classes are immutable, it means that you cannot change the primitive value which is boxed in coresponding wrapper class.
I may misunderstand this content. When I compile and run the code below:

the output is: 11

I do not know why
Can anyone explain it for me?
Thanks!
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Integer object is immutable.
The reference to the object is not. You can assign a new reference to the variable but the original object remains unchanged.
 
Duc Ta
Ranch Hand
Posts: 46
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paweł Baczyński wrote:The Integer object is immutable.
The reference to the object is not. You can assign a new reference to the variable but the original object remains unchanged.


Do you mean assigning an another Integer object to the original Integer object i like this:


The output is:
11
11
 
O Shea
Ranch Hand
Posts: 196
3
Java MySQL Database Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Means when you are making any changes then with those changes a new Object gets created .



See firstly above you have created a Wrapper Object whose value is 10 and i is pointing to it.

Now you have done->

Here above with that i+1 a new Wrapper object gets created whose value is 11 but still i is referring to it.

Ok so when you print the value of i it gives you 11. Because reference variable is same but now Objects gets CHANGED. However you can see it by using hashcode() and because both that objects are different so hashcode() comes out to be different.

Relate the Wrapper Classes with String class. Since String class is also immutable means any changes make then a new String object gets created.

See-> String s=new String("O Shea"); //A string object gets created.
         
          s=s.replace("O",G");   // Here because of runtime operation a new Object gets created but still s is referring to it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!