String Interning in Java
String Interning in Java
Java provides a powerful feature called String Interning that helps in saving memory and improving performance. If you’re just getting started with Java, this article will help you understand what string interning is and how it works.
What is String Interning?
String interning is a process in Java where the JVM maintains a pool of unique string literals in a special memory area called the String Constant Pool. When you create a string literal, Java checks this pool first to see if an identical string already exists. If it does, the reference to the existing string is returned. If not, a new string is added to the pool.
String interning helps save memory by avoiding the creation of multiple string objects with the same value. It also makes string comparison faster using the ==
operator since interned strings share the same memory reference.
How to Intern a String manually
You can intern a string explicitly using the intern()
method. This method returns a canonical representation for the string object from the string pool.
Example
public class StringInterningExample {
public static void main(String[] args) {
String str1 = "Java"; // Stored in string pool
String str2 = new String("Java"); // New object in heap
System.out.println(str1 == str2); // false (different references)
System.out.println(str1 == str2.intern()); // true (same reference in pool)
}
}
In the above example, str1
is a string literal and stored in the string pool. str2
is created using the new
keyword and stored in the heap.
When we compare them with ==
, it returns false
because they are different objects. However, when we use intern()
on str2
, it returns the reference from the string pool, making str1 == str2.intern()
return true
.
String interning is a simple yet powerful concept in Java. It allows efficient memory usage and faster string comparisons. As a beginner, understanding this concept will help you write more optimized Java code, especially when working with a large number of strings.
Java Tutorials
Java Tutorial on this website: