Java Object equals() Method
The Object equals() method is used to compare whether two objects are equal.
The equals() method compares two objects by checking whether the two object references point to the same object, i.e., it only checks whether the two objects point to the same memory address.
**Note:** If a subclass overrides the equals() method, it also needs to override the hashCode() method, for example, the String class overrides both the equals() method and the hashCode() method.
Syntax
object.equals(Object obj)
Parameters
-
obj - The object to compare.
Return Value
Returns true if the two objects are equal, otherwise returns false.
Example
The following example demonstrates the use of the equals() method:
Example
class
RunoobTest
{
public
static
void
main
(
String
[
]
args
)
{
//
Object class uses the equals() method
//
Create two objects
Object
obj1
=
new
Object
(
)
;
Object
obj2
=
new
Object
(
)
;
//
Determine whether obj1 and obj2 are equal
//
Different objects with different memory addresses are not equal, returns false
System
.
out
.
println
(
obj1
.
equals
(
obj2
)
)
;
//
false
//
Assign obj1 to obj3
//
String overrides the equals() method
//
Object reference with the same memory address is equal, returns true
Object
obj3
=
obj1
;
System
.
out
.
println
(
obj1
.
equals
(
obj3
)
)
;
//
true
}
}
The execution result of the above program is:
false
true
The String class overrides the equals() method to compare whether two strings are equal:
Example
class
RunoobTest
{
public
static
void
main
(
String
[
]
args
)
{
//
String class uses the equals() method
//
Create two objects
String
obj1
=
new
String
(
)
;
String
obj2
=
new
String
(
)
;
//
Determine whether obj1 and obj2 are equal
//
The two initialized objects are both null, so they are equal, returns true
System
.
out
.
println
(
obj1
.
equals
(
obj2
)
)
;
//
true
//
Assign values to the objects
obj1
=
"
Runoob
"
;
obj2
=
"
"
;
//
Determine whether obj1 and obj2 are equal
//
The two values are different and their memory addresses are also different, so they are not equal, returns false
System
.
out
.
println
(
obj1
.
equals
(
obj2
)
)
;
//
false
}
}
The execution result of the above program is:
true
false
Java Object Class