Thursday 25 September 2014

Java Questions On String

Java interview question: Why Strings are immutable?

Java also has its share of immutable classes which are primarily String class and Wrapper classes In this post, we will understand the need of immutability for String class.

1) Security

The first and undeniably most important reason is security. Well, its not only about your application, but even for JDK itself. Java class loading mechanism works on class names passed as parameters, then these classes are searched in class path. Imagine for a minute, Strings were mutable, then anybody could have injected its own class-loading mechanism with very little effort and destroyed or hacked in any application in a minute.
[ Well, I think in this case java didn't have got any popularity today...
and nobody would be using it]. It means Strings were immutable that’s why java is still around in the game.

2) Performance :

 I believe that it is not the immutability of String class that gives it performance, rather it is string pool which works silently behind the scene. But at the same time, string pool is not a possibility without making String class immutable. So, it all again comes down to immutability of String class which allowed string pools, and thus better performance.

This prints true (even though we don't use equals method: correct way to compare strings)
    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both
s and t point to the same object and some little memory saved.
Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.


3) Thread safety

Immutable objects are safe when shared between multiple threads in multi-threaded applications. Just understand and learn it. There is no super logic. If something can’t be changed, then even thread can not change it.
As String class is main building block of java programming language, because of its use in class loading mechanism, it was indeed a must use case to prevent the String class from being dirty in case of multiple thread. Immutability does the magic here.