When to Use String#intern() on String Literals
String#intern() returns the existing String from the String pool if it's present or adds it and returns the added reference. While String literals are automatically interned, it may still be necessary to invoke intern() manually in certain scenarios.
Automatic Interning of String Literals
In the example code provided:
String s1 = "Rakesh"; String s2 = "Rakesh"; String s3 = "Rakesh".intern();
Both s1 and s3 represent the same String, as interning is implicitly applied to String literals in Java. This is why both lines, s1 == s2 and s1 == s3, evaluate to true.
Use Case for intern()
Using intern() is relevant when dealing with Strings that are not String literals. For instance:
String s1 = "Rakesh"; String s2 = "Rakesh"; String s3 = new String("Rakesh"); String s4 = new String("Rakesh").intern();
In this example, s1, s2, and s4 represent the same String in the constant pool due to automatic interning or explicit invocation of intern(). However, s3 refers to a new String instance that is not in the constant pool.
By explicitly invoking intern() on s4, it effectively checks if "Rakesh" already exists in the String pool. If not, it adds it and returns the reference of the added String. This optimizes String usage by reducing duplicate String objects in memory and promoting string equality comparisons.
The above is the detailed content of When Should You Use `String#intern()` in Java?. For more information, please follow other related articles on the PHP Chinese website!