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.
p
Compile Time Concatenation String computed by constant expression are done at compile time and treated as constants or literals means the value of the string or expression is known or evaluated at compile time hence the compiler can check the same value in string pool and the return the same string object reference.
Runtime Concatenation String expressions whose values are known or can not be evaluated at compile but depends on the input or condition of run-time then the compiler will not know the value of the string and hence always land up using StringBuilder to append the string and always returns a new string . I guess this example will clarify it better.
public static void main(String[] args) {
new StringPoolTest().run();
}
String giveLiteralString() {
return "555";
}
void run() {
System.out.println("555" + 9 == "555" + 9);
System.out.println("555"+Integer.valueOf(9) == "555" + Integer.valueOf(9));
System.out.println(giveLiteralString() == giveLiteralString());
// The result of runtime concatenation is a fresh string.
System.out.println(giveLiteralString() == giveLiteralString() + "");
}