wood burning stoves 2.0*
The moose likes Java in General and the fly likes Using Strings  we can't Modify the content,Explain it Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using Strings  we can Watch "Using Strings  we can New topic
Author

Using Strings we can't Modify the content,Explain it

sirisha makkapati
Ranch Hand

Joined: Dec 10, 2006
Posts: 83
Any One..

Using Strings we can Reassign the Value,We can Replace the String && We Can Get Substring,But we are Saying Strings are Immutable We Can't Change Content.
Any one please Explain me abot this..

Thanks...
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
Every time you do all those actions a new String object is created.

See the Java Language Specification:

The Class String

String Literals

Java offers other classes that let you really alter the contents of a String. That is the case of java.lang.StringBuffer and since JDK 1.5 there is also java.lang.StringBuilder, which is an unsynchronized, enhanded version of this latter.

I hope this helps!
[ December 16, 2006: Message edited by: Edwin Dalorzo ]
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi Sirisha,

try this:

It will print "Hello", not only "H". Because the String object made in the first line and reference by s is "Hello" and will never change.

If the second line was
s = s.substring (0,1);
the object from the first line also would not be changed. Instead a new string object would be created:"H" and the variable s would refer it. It would just print "H".

The reason why Strings is the String pool. If later in the program a String "Hello" would be used again, no new object would be created. Just the new variable would point to the already existing "Hello" object in the String pool to save resources.
This pooling would not be possible, if Strings were not immutable.


Yours,
Bu.


all events occur in real time
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using Strings we can't Modify the content,Explain it