I recently went back to the String comparisons in Java and tried this:
String s = "hello";
System.out.println(s == "hello");
System.out.println(s.equals("hello"));
When I run it with jdk 19.0.1, Both expressions evaluate to true
despite IDE warnings.
This is obviously against all my intuition, as I've been told since my very first day programming in Java that the first expression should be evaluate to false
because they are different objects. My best guess is that Java has done some optimization at some point to override String comparison with ==
, only I would like to know when did they do that.
Does anyone remember in which Java version has this optimization been done? Thanks.