How to distinguish between == and .equals() method in Java
Contents
[NOTE] Updated October 8, 2023. This article may have outdated content or subject matter.
Generally speaking, equals()
and "=="
operator are used to compare whether two objects are equal, but there are many differences between the two:
- The main difference is that
.equals()
is a method,==
is an operator. - Use
==
to compare references, referring to whether they point to the same memory address. Use.equals()
to compare the content of objects, comparing values. - If
.equals
is not overridden, it will default to calling the nearest superclass to override this method. - Sample code:
|
|
Output:
|
|
Explanation: Here we create two objects named s1
and s2
.
s1
ands2
are references to different objects.- When we use
==
to compares1
ands2
, the return isfalse
, because the memory space they occupy is different. - When using
.equals()
, because only the value is compared, the result istrue
.
Let’s understand the specific differences between these two:
Equal operator (==)
We can use the ==
operator to compare each primitive type (including boolean type), and it can also be used to compare custom types (object types)
|
|
Output:
|
|
If we use ==
to compare custom types, we need to ensure parameter type compatibility (either a subclass and superclass relationship, or the same type). Otherwise, we will produce a compile error.
|
|
Output:
|
|
.equals()
In Java, using equals()
for String
comparison is based on the data/content of the String
, that is, the value. If all their contents are the same and are of String
type, it will return true
. If all characters do not match, it will return false
.
|
|
Output:
|
|
Explanation: Here we use the .equals
method to check whether two objects contain the same value.
- In the above example, we created 3 thread objects and two string objects.
- In the first comparison, we compare whether
t1==t3
, as we all know, the reason for returning true is because t1 and t3 are references to the same object. - When we use
.equals()
to compare twoString
objects, we need to determine whether the two objects have the same value. - The
String
"GEEKS"
object contains the same"GEEK"
, so it returnstrue
.
Article author: Bishal Kumar Dubey Translator: xiantang Original article address: Difference between == and .equals() method in Java
Author xiantang
LastMod 2023-10-08 (049e9a9b)