☰ See All Chapters |
intern() method in Java
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.
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.
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".
All Chapters