Junior
Mis on stringide bassein Java-s?
sobes.tech AI
Vastus AI-lt
String pool is a special memory area in Java's heap where string literals and interned strings are stored. Its main purpose is to save memory by reusing identical string values.
How it works:
When a string literal (e.g., "hello") is created, the JVM first checks if a string with the same value already exists in the string pool.
- If it exists: JVM returns a reference to the existing object in the pool.
- If it does not exist: JVM creates a new
Stringobject in the pool and returns a reference to it.
Creating strings and the pool:
- Using a string literal:
// "hello" is a string literal String s1 = "hello"; String s2 = "hello"; // s1 and s2 refer to the same object in the pool - Using the
new String()constructor:String s3 = new String("world"); String s4 = new String("world"); // s3 and s4 refer to different objects, even if the value is the same. // The string literal "world" may be in the pool, but s3 and s4 are not. - Using the
intern()method:String s5 = new String("java"); // The intern() method checks if a string with the same value exists in the pool String s6 = s5.intern(); // If it exists, returns a reference to the pooled object // If not, adds the current string to the pool and returns a reference to it
Advantages of the pool:
- Memory savings: Reduces the number of duplicated string objects.
- Performance improvement: Comparing string literals (
==) can be faster than comparingStringobjects withequals(), if both operands refer to the same object in the pool.
Important:
The == operator checks if two variables refer to the same object in memory. To compare string contents, always use the equals() method:
String str1 = "abc"; // in the pool
String str2 = "abc"; // in the pool, same reference
String str3 = new String("abc"); // outside the pool
String str4 = str3.intern(); // in the pool, same reference as `str1` and `str2`
System.out.println(str1 == str2); // true
System.out.println(str1 == str3); // false
System.out.println(str1 == str4); // true
System.out.println(str1.equals(str3)); // true