0

I fail to understand the outputs below:

System.out.println(s1.equals(s2)+"a");  ->truea

System.out.println(s1==s2+"a");         ->false

Where s1 & s2 are declared as same String "abc" i.e String s1="abc"; String s2="abc";

n00begon
  • 3,503
  • 3
  • 29
  • 42
Pankaj Kumar
  • 255
  • 5
  • 17

3 Answers3

6
s1==s2+"a"

means the same as

s1==(s2+"a")

because == has lower precedence than +.

eugene82
  • 8,432
  • 2
  • 22
  • 30
3

According to the Oracle documentation the + operator has higher precedence than equality check.

n00begon
  • 3,503
  • 3
  • 29
  • 42
Artem Moskalev
  • 5,748
  • 11
  • 36
  • 55
-3

Because s1 is one string object while s2 is another string object. They have different memory addresses.

LuckyLuke
  • 47,771
  • 85
  • 270
  • 434
  • It is not really true. String literals are stored in small tables, and new variables are given access to those. It means that if you declare it like new String("abc") == new String("abc"), it will give false, but in the OP question it should give true. – Artem Moskalev Dec 01 '13 at 14:11
  • @ArtemMoskalev it definitely should not. – Woot4Moo Dec 01 '13 at 14:12
  • 3
    @Woot4Moo, String a = "abc"; String b = "abc"; a == b gives true. You can check. – Artem Moskalev Dec 01 '13 at 14:13