Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java intern() Method

Java intern() Method

Java String ClassJava String class


The intern() method is used to add a string to the internal string pool at runtime and return the reference from the string pool.

When the intern() method is called, if the string constant pool already contains the string, the reference in the pool is returned; if the pool does not contain the string, it is added to the pool and the string's reference is returned.

**The intern() method follows this rule:** for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

String s1 = new String("Hello");
String s2 = "Hello";
String s3 = s1.intern();

System.out.println(s1 == s2);  // false
System.out.println(s2 == s3);  // true

Syntax


public String intern()

Parameters

Return Value

The return value of the intern() method is the reference of the string in the string constant pool (String Pool).

Return value rules:

Java Version Differences:

Example

The following example demonstrates the use of the intern() method:

Example

public

class

RunoobTest

{

   

public

static

void

main

(

String

args

[

]

)

{

       

// str1 is directly assigned the string literal "Runoob", which is stored in the string constant pool (String Pool)

       

String

str1

=

"Runoob"

;

       

// str2 is created with the new keyword and is stored in heap memory

       

String

str2

=

new

String

(

"Runoob"

)

;

       

// str3 is the reference obtained after calling the intern() method on str2

       

// The intern() method puts "Runoob" into the string constant pool and returns the reference in the pool

       

String

str3

=

str2.

intern

(

)

;

       

// Compare str1 and str2

       

// str1 points to "Runoob" in the constant pool, while str2 points to an object in heap memory

       

// Because their addresses are different, the result is false

       

System

.

out

.

println

(

str1

==

str2

)

;

 

// false

       

// Compare str1 and str3

       

// str3 is the reference returned after str2 calls the intern() method, and it points to "Runoob" in the constant pool

       

// Since str1 also points to "Runoob" in the constant pool, their addresses are the same and the result is true

       

System

.

out

.

println

(

str1

==

str3

)

;

 

// true

   

}

}

Code explanation:

String str1 = "Runoob";

String str2 = new String("Runoob");

String str3 = str2.intern();

-

If it exists, returns the reference of that string;

-

If it does not exist, adds it to the constant pool and returns the reference in the pool.

System.out.println(str1 == str2);

System.out.println(str1 == str3);

The execution result of the above program is:


false
true

Java String ClassJava String class