• Post Reply Bookmark Topic Watch Topic
  • New Topic

String immutability  RSS feed

 
P Teng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String are supposed to be immutable, how ever it seems from below that even Integer could be immutable as well, can some one please explain that when we assign an Integer reference to another the same String immutable behaviour happens. Even though Integer j is assigned a reference to Integer i, and when I change i, j remains unaffected. Can some one please explain



output is
 
Rahul P Kumar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those wrapper classes are immutable.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The wrapper classes (Integer, Long, Short, Byte, Character, Boolean, Float, Double) are indeed also immutable.

Note that what you see happening also has to do with autoboxing. If you do something like i += 10; where i is an Integer object, this will be translated by the compiler to something like this:

So, afterwards, i will refer to another Integer object, while j still refers to the old one.
 
P Teng
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. This helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!