String
is immutable in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. In fact none of methods defined in the String class modify the object's own value . They all create new String objects.
newString.replace('a', 'A');
System.out.println(newString) ; // Will print Game
Due to strings are immutable we can achieve
- Security - String is widely used as a parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and this can lead to a serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause a security problem in Reflection too, as the parameters are strings.
- Safe in threads - immutable objects can not be changed, they can be shared among multiple threads freely.
- String Pool - When string is created and if the string
already existing in the pool without using key word new ,then
reference of existing string will be return , instead of creating
new object.
ex :- String newStingOne = "ABAC" ;
String newStingTwo = "ABAC" ;
Above code will create only one string object in the heap.
- If a string is going to remain constant throughout the program, then use String class object because a String object is immutable. You should use StringBuilder class when we have larger strings or modifying the contents of a string often .Doing that will increase performance.If a string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough. If a string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.
- Class StringBuffer provides same functionality StringBuilder provides minus the additional feature of synchronized methods
References Used :- why-string-is-immutable-in-java
:- OCA Java SE 8 Programer 1 Guide by Mala Gupta
No comments:
Post a Comment