• Post Reply Bookmark Topic Watch Topic
  • New Topic

String immutability  RSS feed

 
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
 
Marshal
Posts: 57238
175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please search JavaRanch, since his question crops up frequently.
 
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.
 
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.
 
That which doesn't kill us makes us stronger. I think a piece of pie wouldn't kill me. Tiny ad:
The WEB SERVICES and JAX-RS Course
https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!