The Java String intern() method returns the interned string. The intern method returns the canonical representation of a String. Here are some examples through which you will understand the working of this method.
Java String intern():
Method signature:
The signature for an intern() method is as shown below.
public String intern()Method parameters and return type:
Return type: It returns an interned string.
Parameters: It doesn’t take any parameters.
Throws: It throws NullPointerException if the string is null.
Example 1:
In this example, we have compared two strings with the same values, but one of them is created by using a new keyword. By using the intern() method with the second string, we have initialized the third string.
Source code:
public class Example1 {
    public static void main(String args[]) {
        String str1 = "This is a Java tutorial";
        String str2 = new String("This is a Java tutorial");
        String tempString = str2.intern();
        
        System.out.println(str1 == str2); 
        System.out.println(str1 == tempString);  
    }
}
Output:
run:
false
true
BUILD SUCCESSFUL (total time: 3 seconds)
Example 2:
Here is another example that will make your concept clear about the intern() method.
Source code:
public class Example2 {
    public static void main(String[] args) {
        String str1 = "Hello world";
        String str2 = str1.intern();
        String str3 = new String("Hello world");
        String str4 = str3.intern();
        
        System.out.println(str1 == str2);  
        System.out.println(str2 == str4); 
        System.out.println(str1 == str3);        
        System.out.println(str3 == str4);           
    }
}
Output:
run:
true
true
false
false
BUILD SUCCESSFUL (total time: 0 seconds)
Example 3:
You can also directly use the intern() method while initializing a string. Here is an example for this concept:
Source code:
public class Example3 {
    
    public static void main(String[] args) {
        String str1= "Java tutorials";
        String str2= new String("Java tutorials").intern();
        System.out.println(str1 == str2);
    }
}
Output:
run:
true
BUILD SUCCESSFUL (total time: 0 seconds)
References:
Happy Learning 🙂
