How do you use string pool and interning with a simple code example?

In Java, the string pool is a special storage area in the heap for strings. When you create a string literal, Java checks to see if that string already exists in the string pool. If it does, Java returns a reference to the existing string; if not, it adds the new string to the pool. Interning strings is a method used to ensure that all identical string literals share a single memory reference.

Example of String Pool and Interning

public class StringPoolExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello").intern(); System.out.println("str1 == str2: " + (str1 == str2)); // true, both refer to the same string pool instance System.out.println("str1 == str3: " + (str1 == str3)); // true, str3 is interned and refers to the same instance } }

keywords: Java string pool interning string literal memory reference