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.
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.
Use
String s=”abc” ;
instead of
String s=new String(“abc”);
wherever required.