1.

Why Is String Immutable In Java ?

Answer»

1. STRING Pool:

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode:

If string is not immutable, One can CHANGE its hashcode and hence not fit to be cached.

3. Security:

String is widely USED as parameter for many JAVA classes, e.g. network connection, opening files, etc. MAKING it mutable might possess threats due to interception by the other code segment.

1. String Pool:

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode:

If string is not immutable, One can change its hashcode and hence not fit to be cached.

3. Security:

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.



Discussion

No Comment Found