When should we use intern method of String on String constants?

Answer

Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.

Since interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String()

Using your example:

String s1 ="Rakesh";String s2 ="Rakesh";String s3 ="Rakesh".intern();String s4 =newString("Rakesh");String s5 =newString("Rakesh").intern();if( s1 == s2 ){System.out.println("s1 and s2 are same");// 1.}if( s1 == s3 ){System.out.println("s1 and s3 are same");// 2.}if( s1 == s4 ){System.out.println("s1 and s4 are same");// 3.}if( s1 == s5 ){System.out.println("s1 and s5 are same");// 4.}

will return:

s1 and s2 are same
s1 and s3 are same
s1 and s5 are same

All string Questions

Ask your interview questions on string

Write Your comment or Questions if you want the answers on string from string Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---