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
After decompiling this line
System.out.println("555" == "555" + "");
I got this bytecode
LINENUMBER 8 L0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ICONST_1
INVOKEVIRTUAL java/io/PrintStream.println(Z)V
...
which is equivalent to
System.out.println(true);
that means expression "555" == "555" + ""
compiles to boolean true
.
For giveLiteralString() == giveLiteralString() + ""
javac built this bytecode
LINENUMBER 8 L0
INVOKESTATIC Test1.giveLiteralString()Ljava/lang/String;
NEW java/lang/StringBuilder
DUP
INVOKESTATIC Test1.giveLiteralString()Ljava/lang/String;
INVOKESTATIC java/lang/String.valueOf(Ljava/lang/Object;)Ljava/lang/String;
INVOKESPECIAL java/lang/StringBuilder.(Ljava/lang/String;)V
INVOKEVIRTUAL java/lang/StringBuilder.toString()Ljava/lang/String;
IF_ACMPNE L1
...
which is equivalent to
if (giveLiteralString() == new StringBuilder(giveLiteralString()).append("").toString()) {
...
which will always produce false since here we're comparing 2 disctinct objects.