• Post Reply Bookmark Topic Watch Topic
  • New Topic

why immutable string object ?  RSS feed

 
Vijay Rathi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Please tell me why immutable string object in java???

Thanks
bye
rathi.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might mean any of these:

a) Why was String made immutable, or b) why is the String class considered to be immutable, or c) what does "immutable" mean?

All of these are beginner questions, so I'm moving this to Java in General (Beginner).
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you create a string using new operator , it creates the string object for you in the heap.But when you create a string using a construct similar to below then it creates the string in the string pool and before creating it checks whether a equivalent object is already present there or not.If yes ; then it returns the reference back.

String s = "ab";

As strings are made immutable therefore multiple references to the same object can be returned safely.
You can see that the string class in final , so that none of its methods could be overriden.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!