Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Pool behavior

Tags:

java

string

pool

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));
like image 241
Jaxox Avatar asked Jan 23 '13 21:01

Jaxox


People also ask

What is string pooling?

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.

How does a string constant pool work?

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.

What is the difference between string pool and heap?

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.

What is advantage of string constant pool?

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.


1 Answers

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".

like image 118
Mirko Adari Avatar answered Oct 22 '22 03:10

Mirko Adari