I read this Questions about Java's String pool and understand the basic concept of string pool but still don't understand the behavior.
First: it works if you directly assign the value and both s1 and s2 refer to the same object in the pool
String s1 = "a" + "bc";
String s2 = "ab" + "c";
System.out.println("s1 == s2? " + (s1 == s2));
But then if I change the string s1+="d", then the pool should have a string object "abcd"? then when I change the s2+="d", it should find the string object "abcd" in the pool and should assign the object to s2? but it doesn't and they aren't referred to the same object. WHY is that?
String s1 = "abc";
String s2 = "abc";
System.out.println("s1 == s2? " + (s1 == s2));
s1 += "d";
s2 += "d";
System.out.println("s1 == s2? " + (s1 == s2));
String pool is a storage space in the Java heap memory where string literals are stored. It is also known as String Constant Pool or String Intern Pool. It is privately maintained by the Java String class. By default, the String pool is empty.
The String constant pool is a special memory area. When we declare a String literal, the JVM creates the object in the pool and stores its reference on the stack. Before creating each String object in memory, the JVM performs some steps to decrease the memory overhead.
The Java string constant pool is an area in heap memory where Java stores literal string values. The heap is an area of memory used for run-time operations.
The main advantage of the string pool in Java is to reduce memory usage. When you create a string literal: String name = "John"; Java checks for the same value in the string pool.
Strings are guaranteed to be pooled when you call String.intern()
on a string.
String s1 = "abcd".intern();
String s2 = "abc";
s2 += "d";
s2 = s2.intern();
s1 == s2 // returns true
When compiler sees a constant it's smart enough to optimize and pool the string literal, i.e.:
String s1 = "abcd";
String s2 = "abcd";
s1 == s2 // returns true
Java Language Specification states:
Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.
So in the case of s2 += "d"
, compiler wasn't as clever as you are and just pooled "d"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With