I switched lecturers today and he stated using a weird code to me. (He said it's better to use .equals
and when I asked why, he answered "because it is!")
So here's an example:
if (o1.equals(o2)) { System.out.println("Both integer objects are the same"); }
Instead of what I'm used to:
if (o1 == o2) { System.out.println("Both integer objects are the same"); }
What's the difference between the two. And why is his way (using .equals
) better?
Found this on a quick search but I can't really make sense of that answer:
In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method.
== checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.
== is a final method, and calls . equals , which is not final. This is radically different than Java, where == is an operator rather than a method and strictly compares reference equality for objects.
Difference between == and . Equals method in c# The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.
In Java, ==
always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals
method can be overridden - so two distinct objects can still be equal.
For example:
String x = "hello"; String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' }); System.out.println(x == y); // false System.out.println(x.equals(y)); // true
Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:
String x = "hello"; String y = "he" + "llo"; System.out.println(x == y); // true!
Here x
and y
are references to the same string, because y
is a compile-time constant equal to "hello"
.
The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With