• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How Strings are immutable ?

 
siva chaitanya
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In the above code we are changing the state of String str1 object to upper case but immutable means we cannot change the state of the object then how is it possible..
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You aren't changing the state, you're getting a new object.

Try this instead, and you'll see the difference.

 
siva chaitanya
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Matthew i got it String object state cannot be changed but StringBuffer object state can be changed means mutable
 
siva chaitanya
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And what is the difference between these two lines


Both are used to create objects of String?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That last question has been asked before, last time was just a few days ago.
 
siva chaitanya
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you jesper i got it
 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don’t use StringBuffer for mutable Strings unless you need sunchronisation. Most of the time StringBuilder gives better performance.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic