I have been told in a Java course at my university that I should never compare Java strings with the ==
operator, because it checks if two strings are the same object instead of checking if they have the same characters.
However, on the day of the exam, I am presented with the following code:
if ("String".toString() == "String")
System.out.println("The same");
else
System.out.println("Not the same");
I thought the result was going to be "Not the same", because "String".toString()
and "String"
are not the same object.
However, the console prints "The same"!. ¿How does string comparison with ==
actually work?