Home >Java >javaTutorial >When Should You Use the `intern()` Method for Java Strings?
When to Use the intern Method for String Literals
Strings created using literal syntax ("String") are automatically interned in the String pool by JVM. Consequently, == operator behaves consistently for String literals.
However, interning is not automatic for Strings created with new String(). This is where the intern() method becomes relevant.
Using the intern() method on a String created with new String() will add that String to the pool and return the existing object instance if the same String already exists in the pool.
For example:
String s1 = "Rakesh"; String s2 = "Rakesh"; String s3 = "Rakesh".intern(); String s4 = new String("Rakesh"); String s5 = new String("Rakesh").intern(); if (s1 == s2) { System.out.println("s1 and s2 are same"); } if (s1 == s3) { System.out.println("s1 and s3 are same"); } if (s1 == s4) { System.out.println("s1 and s4 are same"); } if (s1 == s5) { System.out.println("s1 and s5 are same"); }
The output will be:
s1 and s2 are same s1 and s3 are same s1 and s5 are same
In all cases except for s4, where the String was explicitly created using new and not interned, the JVM's string constant pool returns the same immutable instance.
Refer to JavaTechniques "String Equality and Interning" for more detailed information.
The above is the detailed content of When Should You Use the `intern()` Method for Java Strings?. For more information, please follow other related articles on the PHP Chinese website!