• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic