When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo
It works in your case (and AFAIK it has been working like that in earlier JVMs as well) because s refers to the string literal "hello". String references initialized with literals refer to the literal (which is a global object in the background), not a separately created new object. The term for this, as others have mentioned too, is interning. Thus s and "hello" in your example refer to the same physical object. Consider
String s1 = "hello";
String s2 = "hello";
String s3 = "hello";
All of these strings refer to the same physical object, thus '==' comparison between any pair of these, or between any of them and "hello" returns true.
However
String s4 = new String ("hello");
creates a new object, thus s4 == "hello" yields false.