Java String intern() Method with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

The intern() method in Java is a powerful tool for optimizing memory usage and improving the performance of Java applications. Java, a language widely used for its robust string handling, stores string objects in a unique memory area called the String Constant Pool.

When a string is created in Java, it’s first checked in this pool. If a matching string exists, the existing reference is returned, saving memory and processing resources. If not, a new entry is added to the pool, ensuring only one unique copy of a string resides in memory. This mechanism is the cornerstone of Java’s memory management strategy, and intern() is the key to unlocking these benefits.

intern() not only conserves memory but also streamlines Java applications. When working with strings, especially during intensive operations like parsing large data, the creation of new string objects can be resource-intensive.

intern() allows developers to alleviate this overhead by reusing existing strings from the String Constant Pool. This results in efficient memory utilization, reduces the need for frequent garbage collection, and ultimately enhances the performance of Java applications.

In this article, we will explore the inner workings of the intern() method, examine its practical applications, and learn how to leverage it to optimize Java programs.

Method Signature

The intern() method is a public instance method defined in the String class. It has the following method signature:

public String intern()

The intern() method returns a String, which is the canonical representation of the string value.

Need and Working of String.intern()

By default, String objects in Java are stored in the Heap memory.

For example:

String s1 = "Hello"; 
String s2 = "Hello";

Here, s1 and s2 refer to two different objects in the Heap. Strings are immutable in Java.

However, the String pool stores a single copy of the String. The intern() method checks if the String already exists in the pool:

  • If yes, it returns the reference to the pooled String object.
  • If not, it adds the String to the pool and then returns the reference.

For example:

String s1 = new String("Hello");
String s2 = s1.intern();

Here, s2 will refer to the same String object as s1 in the String pool.

Java String intern() Method Examples

Example 1

public class InternExample {

  public static void main(String[] args) {
    String s1 = new String("Hello");
    String s2 = s1.intern();

    System.out.println(s1 == s2); //false

    String s3 = "Hello";
    String s4 = "Hello"; 

    System.out.println(s3 == s4); //true
  }
}

Output:
false
true

Here, s1 and s2 refer to different objects, as s1 was created using a new keyword.

Meanwhile, s3 and s4 refer to the same string object from the pool.

Example 2

public class InternExample2 {

  public static void main(String[] args) {
    String s1 = new String("Hello");
    String s2 = "Hello";
    s1.intern();

    System.out.println(s1 == s2); //false
  }
}

Output:
false

Here, even after interning s1, it refers to a different object than s2. Because s1 was already created explicitly earlier.

Key Points

  • String literals like “Hello” are automatically interned.
  • The new keyword always creates a new object.
  • Calling intern() on an existing String does not replace the original String.

So, in most cases, explicitly calling intern() is unnecessary since string literals are automatically interned.

Conclusion

In conclusion, Java’s intern() method optimizes memory and performance by reusing existing String objects from the String Constant Pool. It returns the canonical representation of a string, reducing the need to create new objects. While useful, it’s important to note that string literals are automatically interned, and calling intern() on them is usually unnecessary. Careful consideration of when to use this method can help strike a balance between memory efficiency and code simplicity, ultimately improving application performance.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

Leave a Reply

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