What is an intern() method in the String class? December 28, 2017July 23, 2020 Rakesh2 Comments What is intern() method in the String class?
2 thoughts on “What is an intern() method in the String class?”
In java , a pool of Strings is maintained by the String class. When the intern() method is invoked equals() method is invoked to determine if the String already exist in the pool. If it does then the String from the pool is returned. Otherwise, this String object is added to the pool and a reference to this object is returned. For any two Strings string1 & string2, string1.intern() == string2.intern() only if string1.equals(string2) is true.
It makes sense to use intern() method to reduce duplication of string and take advantage of String pool feature provided by Java. You can use intern() method to intern a String object and store them into String pool for further reuse.
A gud practice is to use String constant pool directly n hence no need of intern() method by adopting below coding habbit.
String s=”abc” ;
String s=new String(“abc”);