Intern() Method

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 = new String("Rakesh");
String s5 = new String("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

When two strings are created independently, intern() allows you to compare them and also it helps you in creating a reference in the string pool if the reference didn't exist before.

When you use String s = new String(hi), java creates a new instance of the string, but when you use String s = "hi", java checks if there is an instance of word "hi" in the code or not and if it exists, it just returns the reference.

Since comparing strings is based on reference, intern() helps in you creating a reference and allows you to compare the contents of the strings.

When you use intern() in the code, it clears of the space used by the string referring to the same object and just returns the reference of the already existing same object in memory.

Popular posts from this blog

Async Task in Android

Shake effect in Android

Example For ListView Using BaseAdapter