This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How Strings are immutable ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How Strings are immutable ?" Watch "How Strings are immutable ?" New topic
Author

How Strings are immutable ?

siva chaitanya
Ranch Hand

Joined: Jul 05, 2011
Posts: 59


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

Joined: Apr 06, 2010
Posts: 4425
    
    8

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

Joined: Jul 05, 2011
Posts: 59
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

Joined: Jul 05, 2011
Posts: 59
And what is the difference between these two lines


Both are used to create objects of String?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14278
    
  21

That last question has been asked before, last time was just a few days ago.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
siva chaitanya
Ranch Hand

Joined: Jul 05, 2011
Posts: 59
Thank you jesper i got it
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Don’t use StringBuffer for mutable Strings unless you need sunchronisation. Most of the time StringBuilder gives better performance.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How Strings are immutable ?