-5
public class Test
{
    public static void main(String args[])
    {
        String a="meow";
        String b=a+"deal";
        String c="meowdeal";
        System.out.println(b==c);
    }
}

According to me == operators compares refrences . So b==c should print "true" But it prints "false" . I checked by printing hashcode of "b"and "c" .

Hashcode of both are same

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
user6664723
  • 23
  • 1
  • 6
  • 1
    The hashcodes of strings are based on the _content_, like `equals`, not the _references_, like `==` . – khelwood Mar 23 '17 at 11:03
  • *According to me == operators compares refrences* then why are you using it to compare values? – Tim Mar 23 '17 at 11:03
  • *According to me == operators compare references* and it does. `b` and `c` refer to completely different objects. – D.Shawley Mar 23 '17 at 11:04
  • You are correct that the `==` operators compares refrences. You are not setting `c` to refer to the same string object as `b`. So `b == c` should return false. Which it seems it does. – Ole V.V. Mar 23 '17 at 11:17

3 Answers3

1

== compares references, but the reference to b and c are different - they're two different String instances although the contain the same content.

If you want to compare the content of both Strings, use equals().

Malt
  • 28,965
  • 9
  • 65
  • 105
1

According to me == operators compares refrences .

That is correct. The == operator compares references if both operands are reference types. (It is not correct if either operand is a primitive type ... but that's a different topic.)

So b==c should print "true" But it prints "false" . I checked by printing hashcode of "b"and "c" .

Your reasoning is incorrect.

   String a = "meow";
   String b = a + "deal";
   String c = "meowdeal";

In fact, when that code has finished b and c refer to different string objects that have the same value. In fact, the JLS states that the + operator creates a new string objext ... unless the expression is a constant expression. (And it doesn't qualify as a constant expression in this case, because a is a variable.)

So b == c is false ... BECAUSE == is comparing references, and the references are different.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You should use b.equals(c) for objects and == for primitive types

shmakova
  • 6,076
  • 3
  • 28
  • 44