java - When should we use intern method of String on String literals -


According to

, the intern method is considered to be returning the string from the string pool if the string string pool Is found, otherwise a new string object will be added to the string pool and will be returned in the context of this string.

So I tried to do this:

  string s1 = "Rakesh"; String s2 = "rakesh"; String S3 = "Rakesh" International (); If (s1 == s2) {System.out.println ("s1 and s2 are equal"); // 1.} if (s1 == s3) {System.out.println ("s1 and s3 are identical"); // 2.}  

I expected that s1 and s3 are identical will be printed because s3 is interned, and s1 and s2 The same will not be printed, but the result is: If both lines are printed, it means that the string constant is given internally by default. But if so, why do we need the intern method? In other words when should we use this method?

This means that in many cases, the == operator works for strings in the same way as That he does for ints or other primitive values.

Since interning is automatic for String literals, intern

use your example:

  string s1 = < String> "Rakesh"; String s2 = "rakesh"; String S3 = "Rakesh" International (); String s4 = new string ("rakesh"); String s5 = new string ("rakesh"). Intern (); If (s1 == s2) {System.out.println ("s1 and s2 are equal"); // 1.} if (s1 == s3) {System.out.println ("s1 and s3 are identical"); // 2.} if (s1 == s4) {System.out.println ("s1 and s4 are identical"); // 3.} if (s1 == s5) {System.out.println ("s1 and s5 are equal"); // 4.}  

will come back:

  S1 and s2 are identical to S1 and S3 similar to S1 and S5  

See for more information.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -