I'm bit confused about the difference between == and .equals, I been searching for answers but still not quite clear. So, I'm wondering is there an example code can demonstrate that when comparing two strings, == and .equals return different results.
Asked
Active
Viewed 43 times
1 Answers
2
You are asking two distinct questions here. There isn't an example where ==
returns true but equals
returns false. That is not possible. Because (as an optimization) equals
checks for reference identity. But even if it did not, it does test for value identity (and that would be the same).
However, there are lots of examples where ==
returns false but equals
returns true. Because ==
tests references. One trivial example,
String a = "A";
String b = new String(a);
System.out.println(a == b);
System.out.println(a.equals(b));

Elliott Frisch
- 198,278
- 20
- 158
- 249