0

I'm preparing for the OCA and I am puzzled by reference equality in strings. So given Case 1:

String s = "Hello";
if("Hello" == s){
    System.out.println("TRUE");//prints TRUE
}else {
     System.out.println("FALSE");
}

But in Case 2:

String s = "";
s += "Hello";
if("Hello" == s){
    System.out.println("TRUE");
}else{
     System.out.println("FALSE"); //prints FALSE
}

I know that strings are immutable, but "==" checks for reference equality, and in the second case "s" is a reference that initially points to an empty string and then points to "Hello". So, why does the second case return false? What am I missing?

Regarding: What is the Java string pool and how is "s" different from new String("s")? In my question, in both cases "s" is a string literal and found in the string pool. The above mentioned questions is about a string literal and a String object (which gets memory allocated).

Regarding: How do I compare strings in Java? My question asks "why", not "how".

@Mark Rotteveel Yes I understand that ""+"Hello" is a different string than "", but we are discussing reference equality where "s" is a reference which first points to a string "", and then the same reference "s" points to another string "Hello". In both cases, before the if-clause, the reference "s" points to "Hello", but the results to the if-clause are different.

Thanks for having a look!

JediCate
  • 396
  • 4
  • 8
  • 5
    `"" + "Hello"` creates a new string. – Mark Rotteveel Nov 20 '17 at 17:13
  • i think you found a compiler opimization ;-) – IEE1394 Nov 20 '17 at 17:13
  • 1
    ["The String object is newly created (§12.5) unless the expression is a constant expression (§15.28)."](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1) It's not a constant expression, because `s` isn't final (nor can it be, because you're using `s += ...`). – Andy Turner Nov 20 '17 at 17:21
  • Well, (for anyone who lands on this page) after some further "digging" it turns out @Mark Rotteveel answer is correct. In Java, concatenation creates a new String object which gets memory allocated in the heap. Basically when the compiler sees a concatenation it internally creates that new String object. – JediCate Nov 26 '17 at 12:12

0 Answers0