English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java String intern() usage and example

Java String (String) Methods

The Java String intern() method returns the canonical representation of the string object.

The syntax of the string intern() method is:

string.intern()

Here, string is an object of the String class.

intern() parameters

  • Without any parameters

intern() return value

  • Returns the canonical representation of the string

What is Java String Interning?

String interning ensures that all strings with the same content use the same memory.

Assuming we have two strings:

String str1 = "xyz";
String str2 = "xyz";

Since both strings1and str2with the same content, so these two strings will share the same memory. Java automatically inserts string literals.

However, if a string is created using the new keyword, these strings will not share the same memory. For example,

class Main {
  public static void main(String[] args) {
    String str1 = new String("xyz");
    String str2 = new String("xyz");
    System.out.println(str1 == str2); // false
  }
}

It can be seen from this example that both strings are 'str'1and str2have the same content. However, they are not equal because they do not share the same memory.

In this case, you can manually use the intern() method to use the same memory for strings with the same content.

Example: Java String intern()

class Main {
  public static void main(String[] args) {
    String str1 = new String("xyz");
    String str2 = new String("xyz");
    //str1and str2do not share the same memory pool
    System.out.println(str1 == str2); // false
    //uses the intern() method
    //Now, str1and str2both share the same memory pool
    str1 = str1.intern();
    str2 = str2.intern();
    System.out.println(str1 == str2); // true
  }
}

As you can see, str1and str2has the same content, but they are not equal at first.

Then, we use the intern() method so that str1and str2uses the same memory pool. After using intern(), str1and str2is equal.

Java String (String) Methods