Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java String intern() method
Syntax and Examples



Understanding the intern() Method

In Java strings are immutable. This means once a string object is created, its value cannot be changed. When you create multiple strings with the same content, Java might (but isn't always required to) store them as separate objects in memory. The `intern()` method provides a way to check if a string already exists in the String pool and reuse it if it does; otherwise, creates an interned copy.

Syntax


public native String intern()

Parameters

The intern() method doesn't accept any parameters.

Parameter Description
N/A This method takes no arguments.

Return Value

The intern() method returns a reference to the interned String object.

Return Type Description
String A reference to the interned String.

Examples

Example 1: Checking for Existing Strings

This example demonstrates how `intern()` can be used to check if a string already exists in the String pool.


String str1 = new String("hello");
String str2 = "hello";
String str3 = str1.intern();

System.out.println(str1 == str2); // false (different objects)
System.out.println(str1 == str3); // true (str3 references the same object as str2)
System.out.println(str2 == str3); //true

false
true
true

Explanation: `str1` is created as a new `String` object in the heap. `str2` is created using a string literal, which automatically gets placed into the String pool (if it doesn't already exist). When we call `intern()` on `str1`, Java checks if an equivalent string exists in the String pool. Since "hello" is already present due to `str2`, str3 points to that existing object. Therefore, `str1` and `str2` are different objects (different memory locations), but `str3` refers to the same object as `str2`. The second comparison demonstrates that str1 now references the String pool's "hello".

Example 2: Memory Optimization

This example illustrates how using `intern()` can help optimize memory usage when dealing with many strings containing identical content.


String str1 = new String("example") + "example";
String str2 = new String("example") + "example";

System.out.println(str1 == str2); // false (different objects)

String internedStr1 = str1.intern();
String internedStr2 = str2.intern();

System.out.println(internedStr1 == internedStr2); // true (same object due to String pool reuse)
false
true

Explanation: In this example, both `str1` and `str2` are created as new string objects. Although their content is the same (“exampleexample”), they reside in different memory locations because they are separate object instances. However, when we call intern() on them, Java recognizes that both strings have the same content, so only one copy of “exampleexample” is stored in the String pool and both internedStr1 and internedStr2 refer to it.

Example 3: Using with `String.valueOf()`

This example shows how using intern() together with `String.valueOf()` can lead to unexpected results if you're not careful.


int num = 10;
String str1 = String.valueOf(num).intern();
String str2 = String.valueOf(num);

System.out.println(str1 == str2); //true (str2 also points to the interned object)
true

Explanation: When you call String.valueOf(num), it creates a string representation of the integer `num` (which is "10"). The intern() method then places this string into the String pool. Because Java reuses objects in the String Pool when possible, subsequent calls to `String.valueOf(num)` will return references to that same interned object.

Important Considerations

The behavior of intern() can be tricky and isn't always predictable. The JVM is free to optimize how the String pool is managed, so you shouldn’t rely on it for guaranteed memory savings or object sharing unless you fully understand its implications.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M