Java Object equals() Method

Java String类Java Object Class


The Object equals() method is used to compare whether two objects are equal.

The equals() method compares two objects and determines whether the two object references point to the same object, i.e., it only checks whether the two objects point to the same address in memory.

Note:If a subclass overrides the equals() method, it needs to overridethe hashCode() method, for example, the String class overrides the equals() method and also overrides the hashCode() method.

Syntax

object.equals(Object obj)

Parameter

  • obj- The object to be compared.

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 ExampleTest { 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 have different memory addresses, so they are not equal, returns false System.out.println(obj1.equals(obj2)); // false //Assign obj1 to obj3 //String overrides the equals() method //Object references have the same memory address, so they are equal, returns true Object obj3 = obj1; System.out.println(obj1.equals(obj3)); // true } }

The above program produces the following result:

false
true

The String class overrides the equals() method to compare whether two strings are equal:

Example

class ExampleTest { 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 = "Example"; obj2 = "Google"; //Determine whether obj1 and obj2 are equal //The two values are different, and the memory addresses are also different, so they are not equal, returns false System.out.println(obj1.equals(obj2)); // false } }

The above program produces the following result:

 true
false

Java String类Java Object Class

Other Extensions