String immutability

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?

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.

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: