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!