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?
Related Topics
Java: Case Insensitive Equals - String Comparison
Info | 0 Comments
Java: Smaller/Larger Comparison of Strings - The operator > is undefined for the argument type(s) java.lang.String
Question | 1 Answer
Android Programming: Send data via HTTP POST request
Tutorial | 0 Comments
Java: Split at point str.split(".") does not work
Question | 1 Answer
Micro SD Memory Cards: Difference between microSD, microSDHC, microSDXC and microSDUC
Info | 12 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
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.
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.
For example, assuming you have two string variables having the same content but different references, the == comparison nevertheless returns false:
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