String intern()

Intern() method available in String class is used to return the string from the String constant pool.

This will reduce the problem of string duplicates in Java.

Whenever we call intern() method of String on any string object, it first checks whether same string is already available in string pool.

If it’s available in pool, same reference will be returned otherwise string literal will be added to string pool and its reference will be returned.

It’s very similar to creating string using literal but only difference is we can call intern() using string object as it’s a non-static method of String class.

And we can use this for any string object which is created using new to get the same string from string pool.

Example:

  1. public class StringInternExample{  
  2. public static void main(String args[]){  
  3. String s1=new String("java");  
  4. String s2="java";  
  5. String s3=s1.intern();//returns string from pool
  6. System.out.println(s1==s2);//false because reference is different  
  7. System.out.println(s2==s3);//true because reference is same  
  8. }
  9. }  
public class StringInternExample{  
public static void main(String args[]){  
String s1=new String("java");  
String s2="java";  
String s3=s1.intern();//returns string from pool 
System.out.println(s1==s2);//false because reference is different  
System.out.println(s2==s3);//true because reference is same  
}
}  




String_intern

When we call s1.intern() in the above code, reference to the string “java” available in string constant pool will be returned and hence s3 will also point to the same reference as s2

Note:
Intern() method always gets a reference from string constant pool If the same string already exists then add new string to the string pool If same string is not available in string pool then return its reference Intern() method helps in reducing the memory overhead very similar to string creation using literal.


When to use string intern() ?


We should prefer to use intern() method when strings are not direct constants and when we need to compare such strings its good to use intern() so that it helps us to compare them by using references from the string pool.

It’s generally used on strings constructed with new operator in order to compare them with ==.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on