Notes4Geeks ...short, crisp notes.

Interned String

Basics.

After interning, all Strings with same content/char array will point to the single string object.

For an interned string, only one copy of the value is stored, in the String pool.

All String literals in java are automatically interned only if there value is completely known at compile time.

We can use "==" operator to compare Strings, but only when the Strings value was known at compile time(which caused it to be interned by default), or if we explicitly did "abc".intern() to the string.

Why String interning?

String interning dramatically decreased the string comparison time.

Normally, String comparison using str1.equals(str2) takes O(N) time because each char of str1 needs to be compared to the corresponding char of str2.

With interned Strings, we know that only one instance of a given String(character array) exists in the system.

So, with interned Strings, we can just check whether two strings are equal by doing an equility check using "="

The above equality check is of O(1), hence it is much faster to compare interned Strings.

String comparison using "==" is O(1) while String comparison using ".equals" is O(N).

Since Strings are very frequently used as keys, in hashmap, String interning helps in increasing the performance.

In Java, String literals whose value is known at compile time, are interned by default.

Examples

// value of str1 is known at compile time, so, its automatically interned.
String str1 = "abcdef";
// same as above
String str2 = "abc";
// same as above
String str3 = "def" ;
// str4 is also "abcdef", but it is not equal to str1 by using "==" operator,
// since the value of str4 is only known at runtime.
String str4 = str2+str3;
// str5 is also "abcdef", but it is equal to str1 by using "==" operator
String str5 = str4.intern();
// value of str6 is same as str1, and since the values of both are known at compile time,
// they are interned by default and are equal using "==" operator.
String str6 = "abcdef";
// prints false;
System.out.println(str1 == str4);
// prints true;
System.out.println(str1 == str5);
// prints true;
System.out.println(str1 == str6);
// prints true, but is O(N);
System.out.println(str1.equals(str4));
// prints true, but is O(N);
System.out.println(str1.equals(str5));
// prints true, but is O(N);
System.out.println(str1.equals(str6));

Recap

String str = "abc";

String newStr = "new" + str;

In this, the String str is interned by default, but not the String newStr, because its value is not known at compile time.

That means the String "yes" in String str = "yes"; is automatically interned.

The String "no" in String str = new String("no"); is not interned, because it specifically creates another String object.