Saturday, July 25, 2015

Why String is immutable or final

## String objects are cached in String pool
String pool is a special storage area in Java heap. 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 and returning its reference.

The following code will create only one string object in the heap.

```

String string1 = "abcd";

String string2 = "abcd";

```

If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

## Allow String to cache its hashcode
The hashcode of string is frequently used in Java (`HashMap`). Being immutable guarantees that hashcode will always the same, so that it can be cached without worrying the changes, no need to calculate hashcode every time it is used.

## Security
String is widely used as parameter for many Java classes, e.g. network connection, opening files, etc. If not immutable, a connection or file would be changed and lead to serious security threat. The method thought is was connecting to one machine, but was not.

```

boolean connect(String s) {

    if (!isSecure(s)) {
        throw new SecurityException();
    }
   
    // here will cause problem, if `s` is changed before this by using other references.
   
    causeProblem(s);
}

```

## Credits

[Why String is Immutable in Java](https://dzone.com/articles/why-string-immutable-java)

[Why String is Immutable or Final in Java](http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html)