Interning a Java
Interning a Java
strings maintained by the Java Virtual Machine (JVM). When you intern a string, the JVM
checks if an equivalent string is already present in the pool. If it is, the existing string
reference is returned; otherwise, the string is added to the pool and its reference is
returned.This concept is primarily used for memory optimization and to facilitate efficient
comparison of string literals. Interning a string can be done explicitly using the intern()
method of the String class.
Here’s a brief example:
String str1 = "Hello"; // This string is automatically interned
String str2 = new String("Hello").intern(); // Explicitly interned