There are quite a few things about String Class in Java which i have learn t recently and wanted to share with all.
a. Why String Class is immutable in Java?
Ans: For Security reasons. e.g. file-name , database-connection-url, etc are treated as Strings. If String is not immutable, any other user can access them and change the name posing serious security risk. Another strong reason as said by Dan Bergh Johnsson is: the class-names are treated as String during Class-loading. If String had been mutable, any-one with a malicious intent would have changed the name to his own-class. For more information, Click Here.
b. What is a String Pool?
Ans: Any String created using the literal way is stored in a String pool i.e String str=”Hello World” . So, if we happen to create any other string literals with the same value, then as part of optimization, the same string reference which is available in the pool will be used rather than a creating a new one. Technically in JVM, it is know as RunTime Constant Pool. All these String literals are stored in non-heap area called as Perm Gen(Permanent Generation). To understand more about String Pool, Click Here. However, if we create a String using the new operator, then ir-respective of the value a new String will be created and also, it won’t be stored in the String Pool.
c. What does String.intern() do?
Ans: It is nothing but internalizing the access to Strings. Whenever, we call the intern() method on a String, the JVM checks if there is a String with the same value in String Pool, if yes, then it will be returned otherwise the String is moved from heap-space to the String Pool(perm-gen). To understand the myths surrounding intern(), Click Here.