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,483
  • 3
  • 27
  • 41
Pankaj Kumar
  • 245
  • 5
  • 16

3 Answers3

6
s1==s2+"a"

means the same as

s1==(s2+"a")

because == has lower precedence than +.

eugene82
  • 7,697
  • 2
  • 20
  • 30
3

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

n00begon
  • 3,483
  • 3
  • 27
  • 41
Artem Moskalev
  • 5,658
  • 11
  • 35
  • 55
-3

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

LuckyLuke
  • 45,605
  • 80
  • 262
  • 423
  • 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