Why String is final in Java

Why String is final in Java? This is a very famous interview question in java commonly asked to mid/junior level developers. The interviewer may not only tries to get into your knowledge about String class, but he is also trying to test your knowledge about immutability of objects, behavior of final keyword and even to string pools or ‘intern’ing of String.

We can say that making String class final is all about making String class immutable. So what is an immutable class? An immutable class is a class which cannot be altered by any means after the creation. To make a class or object immutable we need to do the following.

1. Make the class final.
2. Make all fields final and private.
3. Do not provide any setter methods.(All field values are created through constructor).

If we look into the jdk we can see that all wrapper classes like Integer, Long and Double are made immutable.

So lets discuss about why String class is made as an immutable class by the developers of Java language.

1. Security

String is used for a variety of purposes in Java like reading a file by passing file name as a String argument. Imagine if the String argument(the file name here) is changed at runtime by any means will result in reading the wrong file.

Another situation is where Strings are used as parameters for database connection. So if these parameters are changed after the definition that can cause database connection failure or even more worst situation. So by keeping String immutable we can avoid the above situations.

2. Performance

As immutable objects cannot change their values after creation we can avoid repeated calculation of their properties like hashcode. String caches its hashcode once it is calculated and returns the cached value for later uses.

Another way of increasing performance is through String pools (sometimes called heap). As String literals are used widely, rather than demanding separate memory space, same String literals can share their memory space through a pool. For example consider the following code.

Here s1 and s2 will have same reference as it is kept in a pool. But the problem is if s1 changes its value then s2 also changes. So String pool is made possible by keeping String as an immutable class.

3. Classloading

Strings are used in classloaders . The name of the class to be loaded is identified by passing class name as a String parameter. So if the passing String is changed, then JVM tries to load the incorrect class which can cause many issues. So this is another reason why String is kept as an immutable class.

4. Thread safety

As String is an immutable class we can share the String among multiple threads without a fear in changing the values. The immutability of String ensures us a constant value even after it is been shared among multiple threads.

Leave a Comment

Your email address will not be published. Required fields are marked *