00 Votes

Java: Difference between == and .equals()

Question by Guest | 2016-07-17 at 23:05

In Java you seem to be able to compare a string in two different ways. Once with == and once with .equals().

I have tested both ways and both ways are giving me the same results (TRUE if the string is identical, FALSE if not).

So, why are there two methods for doing the same? Or is there indeed a hidden difference and there are possibilities in which one should prefer one of the ways?

ReplyPositiveNegative
0Best Answer0 Votes

Comparing with == and with .equals() is only leading to the same result if not only the content of the compared variables are equal but also the reference of the compared objects.

  • Comparing with == is testing for an identical reference
  • Comparing with .equals() is testing for an identical content (also in case that the reference is different)

For example, assuming you have two string variables having the same content but different references, the == comparison nevertheless returns false:

String a = new String("abc");
String b = new String("abc");
String c = a;

if (a == b) {}      // FALSE
if (a.equals(b)) {} // TRUE
if (b.equals(a)) {} // TRUE

if (a == c) {}      // TRUE
if (a.equals(c)) {} // TRUE
if (c.equals(a)) {} // TRUE

The variables a and b are independent objects and therefore also have different independent references even though their content is the same. Therefore, the comparison a == b is returning FALSE.

If we want to compare the content instead, we are using .equals(). This returns TRUE because both strings are having the value "abc".

The string c is holding the same reverence as the string a. Therefore, comparing with == as well as with .equals() returns TRUE.
Last update on 2020-09-27 | Created on 2016-07-18

ReplyPositive Negative
Reply

Related Topics

Android Getting Sound Levels

Open Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.