Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange String pool behavior

Tags:

java

string

I've got a question of some strange String pool behavior. I'm using == to compare equal Strings to find out whether they're in the pool or not.

public class StringPoolTest {   public static void main(String[] args) {     new StringPoolTest().run();   }    String giveLiteralString() {     return "555";   }    void run() {     String s1 = giveLiteralString() + "";     System.out.println("555" == "555" + "");     System.out.println(giveLiteralString() == giveLiteralString() + "");   } } 

The output is:

true false 

which is a big surprise for me. Could anyone explain this please? I think something about this is taking place at the compilation time. But why does adding "" to a String makes any difference at all?

like image 773
iozee Avatar asked Jul 08 '13 11:07

iozee


People also ask

What is string pool explain with example?

String pool is an implementation of the String Interring Concept. String Interning is a method that stores only a copy of each distinct string literal. The distinct values are stored in the String pool. String pool is an example of the Flyweight Design Pattern.

Why do we have string pool?

Why do we need String Pool in Java? It is created to decrease the number of string objects created in the memory. Whenever a new string is created, JVM first checks the string pool. If it encounters the same string, then instead of creating a new string, it returns the same instance of the found string to the variable.

Is string constant pool eligible for garbage collection?

Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it can't be expanded at runtime and is not eligible for garbage collection.

What is a string constant pool in Java?

A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.


1 Answers

"555" + "" 

is a compile-time constant, whereas

giveLiteralString() + "" 

isn't. Therefore the former compiles into just the string constant "555" and the latter compiles into the actual method invocation and concatenation, resulting in a fresh String instance.


Also see JLS §3.10.5 (String Literals):

Strings computed by concatenation at run time are newly created and therefore distinct.

like image 200
Marko Topolnik Avatar answered Oct 15 '22 01:10

Marko Topolnik