String in java, favourite topic to any interviewer and can be used to test your understading about java string internals.
Unlike in C/C++ java string are not just a stream of characters, instead an object of class java.lang.String.
String objects are immutable they can be shared!!
Example:
String str1 = "string";
String str2 = "string";
String str3 = new String("string");
String str4 = new String("string");
As shown in figure, the string literals will go and reside in String constant pool. Hence when you are assigning a string value to string object it will search in this space if any matching string is found, the object is made to refer same point. In our case str1 and str2.
While, if you choose to use new, there is turnaround. It behaves as usual object creation and above figure depicts the same. Look at following equivalent expressions,
Using "==" - comparing references
str1== str2 // true, points same location in memory
str1== str3 // false, 2 different locations
str3== str4 // false
Using .equals() - comparing contents
str1.equals(str2) // true, equlas is designed to check the contents of String
str3.equals(str1) // true
str3.equals(str4) // true
what is Immutability with String?
Once a String is constructed, its contents cannot be modified. Otherwise, the other String references sharing the same storage location will be affected by the change, which can be unpredictable and therefore is undesirable.
Ex,
String str1 = "string";
str1 = "hello";
Here, instead of modifying content of str1 to hello, a new string will be constructed and str1 will be assigned with location of hello, leaving "string" dereferenced in memory.
why string is immutable?
- Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
No comments:
Post a Comment