String class and Immutability
String class is immutable.
String class is final so no one can modify behavior of any of the string methods. So, no body can override the String methods to alter the immutability.
String Constant Pool
Java maintains a pool of all string literals in order to minimize the memory usage and for better performance.
This special area of memory called “String constant pool”.
When the compiler encounters a string literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String and no new String literal object is created.
Creating new String
Below statement creates one String object and one reference variable
String str = “Hello”;
If “Hello” is not present is string pool, new String object with “Hello” will be created.
Below statement creates two String objects and one reference.
String str = new String(“Hello”);
When Java encounters the string literal “Hello” in the program, it tries to find a match in the string pool. If there is no String object with the content “Hello” in the string pool, a new String object with “Hello” content is created and added to the string pool. The string literal “Hello” will be replaced by the reference of that new String object in the string pool. Because you are using the new operator, Java will create another string object on the heap. Therefore, two String objects will be created in this case.
– New object is created because of “new” will be in non-pool memory
– Literal “Hello” will be put in the pool.
Common confusion regarding String immutability
Refer to below scenario :
str = new String("String One");
str = new String("String Two");
Now, if you print str it will print “String Two” and not “String One”. Why ??
The reason is, it is the String object in memory that is immutable, not the reference variable of the String type.
Here, str is a reference variable and can point to a new object.
We need to declare str as final, if we do not want str to refer to any other String object after it has been initialized.
Mutable alternatives for String:
StringBuffer and StringBuilder are two mutable alternatives to String.
StringBuffer is mutable but synchronized however StringBuilder is not synchronized.
Both classes have the same methods, except that all methods in StringBuffer are synchronized.
© 2015 – 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post