wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes String immutability Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String immutability" Watch "String immutability" New topic
Author

String immutability

Neelima Mohan
Greenhorn

Joined: May 23, 2010
Posts: 27
why was String class made final and String made immutable?
I have heard answers like better memory mgmt as lot of similar String literals gets formed and its best way is to maintain the String pool.
Has security got to do with it?

Thanks,
Neelima
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
Please search JavaRanch, since his question crops up frequently.
Abhinav Yadav
Ranch Hand

Joined: Nov 08, 2009
Posts: 34
Neelima Mohan wrote:why was String class made final and String made immutable?
I have heard answers like better memory mgmt as lot of similar String literals gets formed and its best way is to maintain the String pool.
Has security got to do with it?

Thanks,
Neelima



To get a more clear view check out for this link here
May be it might clear your doubts.


No Dream Too Big
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
Neelima Mohan wrote:why was String class made final and String made immutable?
I have heard answers like better memory mgmt as lot of similar String literals gets formed and its best way is to maintain the String pool.
Has security got to do with it?

Thanks,
Neelima


As for why they made it final, the books say that String is used so much (practically a primitive type), they wanted to ensure that its functionality was always consistent.

String is also a "special" class in that the compiler and JVM supports overloading the '+" operator to append two strings. If they allowed you to subclass String, and your class had its own member variables, what would the '+' operator do? Should it be that '+' only works for String and any subclass of String doesn't work with '+'? (compiler error?) That's a big problem when, for example, you pass your MyString instance to a function that expects String. The compiler would theoretically allow it, but would using the '+' operator in the function cause a runtime error? I'm sure there are many more scenarios where overloading the '+' operator would require yet more exceptions to the basic rules of Java.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String immutability
 
Similar Threads
Get the characters from String.
Help Needed in EL
Why String in Java is made immutable?
String literal
trim()