Home > Java > javaTutorial > When Should You Use the `intern()` Method for Java Strings?

When Should You Use the `intern()` Method for Java Strings?

Mary-Kate Olsen
Release: 2024-12-06 10:37:11
Original
653 people have browsed it

When Should You Use the `intern()` Method for Java Strings?

When to Use the intern Method for String Literals

Strings created using literal syntax ("String") are automatically interned in the String pool by JVM. Consequently, == operator behaves consistently for String literals.

However, interning is not automatic for Strings created with new String(). This is where the intern() method becomes relevant.

Using the intern() method on a String created with new String() will add that String to the pool and return the existing object instance if the same String already exists in the pool.

For 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");
}

if (s1 == s3) {
    System.out.println("s1 and s3 are same");
}

if (s1 == s4) {
    System.out.println("s1 and s4 are same");
}

if (s1 == s5) {
    System.out.println("s1 and s5 are same");
}
Copy after login

The output will be:

s1 and s2 are same
s1 and s3 are same
s1 and s5 are same
Copy after login

In all cases except for s4, where the String was explicitly created using new and not interned, the JVM's string constant pool returns the same immutable instance.

Refer to JavaTechniques "String Equality and Interning" for more detailed information.

The above is the detailed content of When Should You Use the `intern()` Method for Java Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template