Java String intern() Method

The String.intern() method in Java is used to return a canonical representation for the string object. This method ensures that all identical string values share the same memory location, effectively making them "interned." Interning strings can help save memory and improve performance, especially when dealing with a large number of duplicate string values.

Table of Contents

  1. Introduction
  2. intern Method Syntax
  3. Examples
    • Basic Usage
    • Comparing Interned Strings
    • Handling Edge Cases
    • Real-World Use Case
  4. Conclusion

Introduction

The String.intern() method is a member of the String class in Java. It allows you to store strings in a common pool and ensures that all identical string values share the same memory location. This can be particularly useful for optimizing memory usage when working with a large number of duplicate strings.

intern() Method Syntax

The syntax for the intern method is as follows:

public String intern()

Examples

Basic Usage

The intern method can be used to ensure that two strings with the same value share the same memory location.

Example

public class InternExample {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = new String("Hello");
        String str3 = str1.intern();
        String str4 = str2.intern();

        System.out.println("str1 == str2: " + (str1 == str2));
        System.out.println("str1 == str3: " + (str1 == str3));
        System.out.println("str3 == str4: " + (str3 == str4));
    }
}

Output:

str1 == str2: false
str1 == str3: false
str3 == str4: true

Comparing Interned Strings

When strings are interned, they can be compared using the == operator, which checks for reference equality.

Example

public class CompareInternedStringsExample {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = new String("Java").intern();
        String str3 = "Java";

        System.out.println("str1 == str2: " + (str1 == str2));
        System.out.println("str1 == str3: " + (str1 == str3));
    }
}

Output:

str1 == str2: true
str1 == str3: true

Handling Edge Cases

Example: Interning an Empty String

The intern method can also be used with empty strings.

public class InternEmptyStringExample {
    public static void main(String[] args) {
        String str1 = "";
        String str2 = new String("").intern();

        System.out.println("str1 == str2: " + (str1 == str2));
    }
}

Output:

str1 == str2: true

Real-World Use Case

Example: Optimizing Memory Usage with Interned Strings

One common use case for intern is optimizing memory usage when dealing with a large number of duplicate strings, such as in a text processing application.

import java.util.HashMap;
import java.util.Map;

public class OptimizeMemoryExample {
    public static void main(String[] args) {
        Map<String, Integer> wordCount = new HashMap<>();
        String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};

        for (String word : words) {
            word = word.intern();
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

apple: 3
banana: 2
orange: 1

In this example, the intern method is used to ensure that all occurrences of the same word share the same memory location, reducing memory usage.

Conclusion

The String.intern() method in Java is used for optimizing memory usage and improving performance by ensuring that identical string values share the same memory location. It is particularly useful when dealing with a large number of duplicate strings. By understanding and utilizing the intern method, you can efficiently manage string memory usage in your Java programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top