Category:
JAVA STRING INTERVIEW QUESTIONS AND ANSWERS
In Java, String Interning is a memory optimization technique which ensures all distinct string values share a single copy in a specific memory region called the String Constant Pool. The intern() method is used for interning in Java.
When str.intern() method is called , the JVM performs the following tasks :
- It checks if an identical string already exists in the String Constant Pool.
- If the String is already exists in the String Constant Pool , it returns the reference to that existing String pool
- If the String is not present in the String Constant pool, it adds the String to the String Constant Pool and returns its reference.
Example :
String s1=”Gift”;
String s2=”Gift”;
String s3=new String(“Gift”);
String s4=s3.intern();
System.out.println(s1==s2);//true
System.out.println(s1==s3); //false
System.out.println(s1==s4); //true as both point to the same pool address
