Java.lang Package Classes

Java String - intern() Method



The java.lang.String.intern() method returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class string. When the intern method is invoked, if the pool already contains a string equal to the string object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this string object is added to the pool and a reference to this String object is returned.

Syntax

public String intern()

Parameters

No parameter is required.

Return Value

Returns a string that has the same contents as the given string, but is guaranteed to be from a pool of unique strings.

Exception

NA.

Example:

In the example below, intern() method returns a canonical representation for the string object.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String str1 = new String("Hello");
    String str2 = "Hello";
    String str3 = str1.intern();

    //returns false as reference variables 
    //are pointing to different instances
    System.out.println(str1 == str2); 

    //returns true as reference variables 
    //are pointing to same instance
    System.out.println(str2 == str3); 
  }
}

The output of the above code will be:

false
true

Example:

Lets consider one more example to understand the intern() method.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = str1.intern();
    String str3 = new String("Hello");
    String str4 = str3.intern();

    System.out.println(str1 == str2); //true
    System.out.println(str1 == str3); //false
    System.out.println(str1 == str4); //true
  
    System.out.println();

    System.out.println(str2 == str3); //false
    System.out.println(str2 == str4); //true
    System.out.println(str3 == str4); //false
  }
}

The output of the above code will be:

true
false
true

false
true
false

❮ Java.lang - String