The String.intern() in Java returns the reference of an equal string literal present in the string pool. If there is an existing string literal present in the string pool then its reference is returned. Otherwise, a new string with the same content is created, and the reference of the new string is returned.
Note that, internally, the string equality is checked with String.equals() method.
1. What is String Pool?
Java stores one and only one copy of every distinct string value in the string pool. It helps to reuse strings to save memory during program execution. There may be many references to a string in the running program, but there will be the only one copy of a string inside the string pool.
2. String Literals and Objects
In Java, we can create strings in two ways. The first way is to create string literal, and second way is to create an String object using the new keyword.
String str1 = "hello world"; //String literal String str2 = new String("hello world"); //String object
- When we create a String using the literal (it is also recommended), string literals are always created directly into the string pool.
- When we create a string with new keyword, the string is created in the normal heap memory.
3. String.intern() Method
The String.intern() is a native method that returns a reference to an equal string literal present in the string pool. Note that all string literals are automatically created in the String pool, so the intern() method is useful to String objects created with the new keyword.
The the following program, name variable contains the reference to the String object in the heap. When we call intern(), a new string literal with content “Alex” is created in the string pool. The variable str contains the reference to the string literal created in the pool.
String strObject = new String("Alex"); String strLiteral = strObject.intern(); Assertions.assertFalse(strObject == strLiteral); //Points to different objects Assertions.assertTrue(strObject.equals(strLiteral)); //Same content
Any new string literal created with the same content will point to the object in the string pool.
String newLiteral = "Alex"; Assertions.assertTrue(strLiteral == newLiteral);
As a rule, any two strings s1 and s2, s1.intern() == s2.intern() is true if and only if s1.equals(s2) is true.
In this Java tutorial, we learned to intern a string, and how the string literals are different from string objects. The String.intern() is a natively implemented method and provides very high performance.
Happy Learning !!
References: String Java Doc