0

In 1.8 (JRE 1.8.0_221) this comparison seems to be working where previously comparing two objects with == shouldn't be the same? Is this a case of Java optimising away one of the variables or is something else happening?

public class example
{
    public static void main(String[] args)
    {
        String str1 = "hi";
        String str2 = "hi";

        System.out.println(str1.hashCode());
        System.out.println(str2.hashCode());

        if (str1 == str2)
        {
            System.out.println("wut");
        }
    }
}

Output:

3329
3329
wut
Crizly
  • 971
  • 1
  • 12
  • 33
  • what java version are you running? – Jojo Narte Oct 18 '19 at 10:22
  • @JojoNarte JRE 1.8.0_221 – Crizly Oct 18 '19 at 10:24
  • 1
    Yes, it's an optimization. The string objects created by string literals are [`intern`d](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html#intern()), and so you usually end up with the same object for the same literal (IIRC it's "always," within a single class). This optimization isn't new, and also isn't something you should rely on. – T.J. Crowder Oct 18 '19 at 10:27
  • The idea here is not that `str1==str2` _can't_ or _shouldn't` ever be `true`: obviously it can. It's that most often when `str1.equals(str2) && str1 != str2`; it's only the rarest of coincidences when both `str1.equals(str2) && str1 == str2` – Kevin Anderson Oct 18 '19 at 10:46
  • 2
    Technically, not it isn't an optimization. This is a property that is required by the JLS; see [3.10.5. String Literals](https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.5) *"Moreover, a string literal always refers to the same instance of class String ..."*. And it doesn't just apply within a single class. – Stephen C Oct 18 '19 at 10:52
  • 1
    Please read https://www.journaldev.com/797/what-is-java-string-pool – VadymVL Oct 18 '19 at 11:10
  • @JojoNarte the Java version is irrelevant. This behavior didn’t change since Java 1.0. – Holger Oct 25 '19 at 07:52

0 Answers0