n Java, the intern()
method is used to place a String
object into the internal pool of strings, also known as the string pool. This string pool is a special area in the Java heap memory where literal strings are stored. When you create a string literal (e.g., "hello"
), Java automatically stores it in the string pool. However, strings created using the new
keyword (e.g., new String("hello")
) are not automatically interned unless you explicitly call intern()
on them.
package strings;
public class InternMethodDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2); // false - s1 and s2 point to different objects
System.out.println(s1.equals(s2)); // true - s1 and s2 have the same content
String s3 = s2.intern();
System.out.println(s1 == s3); // true - s1 and s3 point to the same interned string object
}
}
When to Use intern()
:
- Use
intern()
when you need to ensure that multiple string objects with the same content share the same memory location in the string pool. - Use it judiciously to balance memory efficiency and performance considerations, especially in scenarios where string comparisons using
==
are critical.
By understanding how intern()
works, you can leverage it effectively to optimize memory usage and ensure predictable string comparison behavior in your Java applications.