Java String intern() Method

A string object in the string constant pool is called a String Intern. We can create an exact copy of the heap memory string object in a string constant pool.

 

intern():

Returns a canonical representation for the string object.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public String intern()
public String intern()
public String intern()

 

Note: It returns a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

 

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class TestString{
String str1 = "www.w3schools.blog";
String str2;
public void internTest(){
str2 = str1.intern();
System.out.println(str2);
}
}
public class StringInternExample {
public static void main(String args[]){
//creating TestString object
TestString obj = new TestString();
//method call
obj.internTest();
}
}
class TestString{ String str1 = "www.w3schools.blog"; String str2; public void internTest(){ str2 = str1.intern(); System.out.println(str2); } } public class StringInternExample { public static void main(String args[]){ //creating TestString object TestString obj = new TestString(); //method call obj.internTest(); } }
class TestString{
    String str1 = "www.w3schools.blog";
    String str2;

    public void internTest(){
        str2 = str1.intern();
        System.out.println(str2);
    }
}

public class StringInternExample {
    public static void main(String args[]){
        //creating TestString object
        TestString obj = new TestString();
        
        //method call
        obj.internTest();
    }
}

Output

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
www.w3schools.blog
www.w3schools.blog
www.w3schools.blog