Object equals() in Java

equals(): This method is available in java.lang.Object class of Java.

Syntax:

boolean java.lang.Object.equals(Object obj)

This method takes one argument of type Object as its parameter. This method indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relationon non-null object references:

1. It is reflexive: for any non-null reference value x, x.equals(x) should return true.

2. It is symmetric: for any non-null reference values x and y, x.equals(y)should return true if and only if y.equals(x) returns true.

3. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

4. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return trueor consistently return false, provided no information used in equals comparisons on the objects is modified.

5. For any non-null reference value x, x.equals(null) should return false.

Parameters: One parameter is required for this method.

obj: the reference object with which to compare.

Returns: true if this object is the same as the obj argument; false otherwise.

Exceptions: NA

Approach

Java

public class Objectequals {
    public static void main(String[] args) {

        // Integer object
        Object obj = 12;

        // Integer object 2
        Object obj2 = 12;
        System.out.println(obj.equals(obj2));
    }
}

Output:

true


Some other methods of Object Class.

hashCode()This method returns a hash code value for the object.

getClass()The returned Class object is the object that is locked by static synchronized methods of the represented class.

toString()This method returns a string representation of the object.

No comments:

Post a Comment