Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
sirisha makkapati
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chris Ringer
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True, Strings are immutable. But what do we care? Reference variables certainly aren't immutable. If using String and garbage collection becomes a performance issue, use StringBuffer or StringBuilder.

Chris
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!