N
N
NameOf Var2016-11-17 00:10:42
Java
NameOf Var, 2016-11-17 00:10:42

What is the meaning of Object.equals(Object ob) method in Java?

What is the difference between the "==" comparison operator and the Object.equals(Object ob) method? The documentation says that the equals method compares the contents of objects and outputs the boolean true if the contents of the objects match, and false otherwise. However, this is not the case in practice:

public class Application {
    public static void main(String args[]) {
        A a1 = new A(3);
        A a2 = new A(2);
        System.out.println(a1.equals(a2));

    }
}

The result will be false.
And if both links are equated:
public class Application {
    public static void main(String args[]) {
        A a1 = new A(3);
        A a2 = new A(2);
        a1 = a2;
        System.out.println(a1.equals(a2));

    }
}

That result will be true. Can you please tell me what is the difference between the equals method and "==" method? If there is no difference, then what is the point of this method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rou1997, 2016-11-17
@hax

String s1 = "abc";
String s2 = "abc";
s1.equals(s2) // true
s1 == s2 // false

But you yourself must set the logic for it in your class, otherwise how will it understand what "content" to compare, but you usually have more than one field or two in your class?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question