Java String intern() Method Example

1. Introduction

The Java String.intern() method is used to ensure that all identical strings share a single copy in the string pool, which is a location in the Java heap where Java stores literal strings. This method helps in saving memory and improving performance by reusing instances of strings that are identical. This tutorial will demonstrate how the intern() method works with an example.

Key Points

- intern() returns a canonical representation for the string object.

- It checks the string pool first: if the string is not in the pool, it adds it; if it is, it returns the reference from the pool.

- Using intern() can reduce memory usage when many identical strings are used.

2. Program Steps

1. Create two similar strings in different ways.

2. Intern both strings.

3. Check if the interned strings reference the same object.

4. Print the result of the comparison.

3. Code Program

public class StringInternExample {
    public static void main(String[] args) {
        // Create a new String object
        String s1 = new String("Java");
        // Manually force it into the string pool
        String s2 = s1.intern();
        // Retrieve a string from the string pool using literal
        String s3 = "Java";
        // Check if s2 and s3 point to the same object
        boolean isSame = s2 == s3;
        // Print the result
        System.out.println("Do s2 and s3 refer to the same object? " + isSame);


Do s2 and s3 refer to the same object? true


1. String s1 = new String("Java"): Creates a new String object s1 with the content "Java".

2. String s2 = s1.intern(): Invokes intern() on s1. This checks the string pool and adds "Java" to the pool if it isn't there already, and returns the reference to it.

3. String s3 = "Java": Uses string literal to declare s3, which Java automatically places in the string pool during class loading.

4. boolean isSame = s2 == s3: Compares the references of s2 and s3 using == to check if they refer to the same object in memory.

5. System.out.println("Do s2 and s3 refer to the same object? " + isSame): Outputs the result of the reference comparison.