0

why str1==str2 is returning false while str2 == str3 returns true in below code? As per my understanding, str1==str2 should also return true.

public static void main(String[] args) throws Exception {
        String str = "me";
        String str1 = str + "test";
        String str2 = "metest";
        String str3 = "me" + "test";
        System.out.println(str1==str2); // O/P false
        System.out.println(str2==str3); // O/P true

    }
  • 1
    You would get `true` if `str` would be `final`. Without it compiler don't want to assume value of `str` and leaves its evaluation to runtime. If it would be final compiler would *know* it while compiling so it would simply "calculate" it at compilation time which means it would see `str + "test"` as `"me" + "test"` (just like for `str3`) and simply compile it as `"metest"`. See more in second duplicate: [Comparing strings with == which are declared final in Java](https://stackoverflow.com/q/19418427). – Pshemo May 04 '19 at 10:18

1 Answers1

0

String concatenation creates a new string and copies to it the content of the two concatenated strings. That’s why.

Ali Ben Zarrouk
  • 1,891
  • 16
  • 24