Have you heard anything about the intern method in Java?
sobes.tech AI
Answer from AI
Yes, I have heard of it. The intern() method belongs to the String class and is used to manage the string literal pool.
When the intern() method is called on a string object, Java checks if a string with the same content already exists in the string literal pool.
- If a string with the same content exists in the pool, a reference to that existing object is returned.
- If it does not exist, the current string object is added to the pool, and a reference to it is returned.
Thus, intern() guarantees that for identical string values created in different ways (e.g., via new String() or concatenation), the same object from the pool will be used if they are interned.
Advantages of using intern():
- Memory savings: If many strings have the same content,
intern()allows using a single object in memory instead of creating multiple duplicates. - Fast comparison: Comparing interned strings with
==becomes possible and faster than comparing string contents withequals().
Example:
// Creating strings in different ways
String s1 = "hello"; // Created in the literal pool
String s2 = new String("hello"); // Created on the heap
System.out.println(s1 == s2); // false, different objects
// Interning s2
String s3 = s2.intern();
System.out.println(s1 == s3); // true, s3 now references the object from the pool
It is important to remember that frequent use of intern() can have a slight impact on performance due to pool search operations. It should be used thoughtfully, especially when there are many duplicate string values. Before Java 7, the string literal pool was located in PermGen Space; from Java 7 onwards, it has moved to the Heap.