×
☰ See All Chapters

intern() method in Java

  1. intern() method is present in String class, but not in StringBuilder and StringBuffer. If you want to use intern() method for  StringBuilder and StringBuffer , then you have to convert  StringBuilder and StringBuffer to String.  

  2. toString() method present in  Object class returns a string representation of the object, can be used to convert  StringBuilder and StringBuffer objects to String object. 

  3. return type of intern() is String. It always returns any one of the String from string constant pool. 

String s1 = new String("Hello Java");

String s2= s1.intern();

Here JVM checks whether "Hello Java" is present in string constant pool. If present then s2 is returned to existing one, otherwise new string constant “Hello Java" is created in string constant pool and s2 is returned to this new string constant  "Hello Java".

intern-method-in-java-0
 
intern-method-in-java-1
 
intern-method-in-java-2
 

All Chapters
Author