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 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"
.