Home > Java > javaTutorial > When Should You Use `String#intern()` in Java?

When Should You Use `String#intern()` in Java?

Mary-Kate Olsen
Release: 2024-12-26 06:06:14
Original
915 people have browsed it

When Should You Use `String#intern()` in Java?

When to Use String#intern() on String Literals

String#intern() returns the existing String from the String pool if it's present or adds it and returns the added reference. While String literals are automatically interned, it may still be necessary to invoke intern() manually in certain scenarios.

Automatic Interning of String Literals

In the example code provided:

String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
Copy after login

Both s1 and s3 represent the same String, as interning is implicitly applied to String literals in Java. This is why both lines, s1 == s2 and s1 == s3, evaluate to true.

Use Case for intern()

Using intern() is relevant when dealing with Strings that are not String literals. For instance:

String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = new String("Rakesh");
String s4 = new String("Rakesh").intern();
Copy after login

In this example, s1, s2, and s4 represent the same String in the constant pool due to automatic interning or explicit invocation of intern(). However, s3 refers to a new String instance that is not in the constant pool.

By explicitly invoking intern() on s4, it effectively checks if "Rakesh" already exists in the String pool. If not, it adds it and returns the reference of the added String. This optimizes String usage by reducing duplicate String objects in memory and promoting string equality comparisons.

The above is the detailed content of When Should You Use `String#intern()` in Java?. 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