• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String immutability

 
Neelima Mohan
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48370
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please search JavaRanch, since his question crops up frequently.
 
Abhinav Yadav
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic