Pages

Wednesday, 4 July 2012

What is the difference between creating a String using the new operator and String intern ?


String s1 = "abcde";

Creating a String in this way is called interning a String.  string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.



String s2 = new String("abcde");
String s3 = "abcde";



String object is an individual instance of the java.lang.String class. s2 will be a new String object.


Hence, 

(s1 == s2) is false
(s1 == s3) is true
(s1.equals(s2)) is true



Why is the String class immutable ? 
String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.


References :


public class StringConstruction {
static String str1 = "You cannot change me!"; // Interned
public static void main(String[] args) {
String emptyStr = new String(); // ""
System.out.println("emptyStr: \"" + emptyStr + "\"");
String str2 = "You cannot change me!"; // Interned
String str3 = "You cannot" + " change me!"; // Interned
String str4 = new String("You cannot change me!"); // New String object
String words = " change me!";
String str5 = "You cannot" + words; // New String object
System.out.println("str1 == str2: " + (str1 == str2)); // (1) true
System.out.println("str1.equals(str2): " + str1.equals(str2)); // (2) true
System.out.println("str1 == str3: " + (str1 == str3)); // (3) true
System.out.println("str1.equals(str3): " + str1.equals(str3)); // (4) true
System.out.println("str1 == str4: " + (str1 == str4)); // (5) false
System.out.println("str1.equals(str4): " + str1.equals(str4)); // (6) true
System.out.println("str1 == str5: " + (str1 == str5)); // (7) false
System.out.println("str1.equals(str5): " + str1.equals(str5)); // (8) true
System.out.println("str1 == Auxiliary.str1: " +
(str1 == Auxiliary.str1)); // (9) true
System.out.println("str1.equals(Auxiliary.str1): " +
str1.equals(Auxiliary.str1)); // (10) true
System.out.println("\"You cannot change me!\".length(): " +
"You cannot change me!".length());// (11) 21
}


No comments:

Post a Comment