-3

Up until now I've always thought that == was a shortcut to Object.equals() in Java. Now I'm not so sure.

Is the == operator a syntactical shortcut to Object.equals()? If not, why not?

As it seems people often confuse this question for "What is the difference between == and Object.equals()", let me clarify: I know the difference and the default behavior. I am asking if the == operator was changed to be a mere link to Object.equals(). If it isn't, then why must it always be an instance comparison and why is this feature not implemented?

einsteinsci
  • 1,137
  • 1
  • 8
  • 22
  • 1
    dude, pls, simply use google -.- –  May 01 '15 at 01:33
  • `Object.equals()` is defined to only test the references, so with Object types it is the same. However, `String` overloads equals... – D. Ben Knoble May 01 '15 at 01:34
  • I have used Google and it does not recognize '==' as part of the question, so all I get are previous answers to the difference between the two in (much older) versions of Java. I thought that the syntactical shortcut thing was a feature of Java 1.6 or 1.7. I understand that in older Java versions, == only compared instances via location in memory, and as does Object.equals() unless overridden. I am asking if this is a feature in the **current** version of Java. – einsteinsci May 02 '15 at 02:02

1 Answers1

1

When applied to object references, the == operator always tests whether two values are references to the same (identical) object. The default behavior of equals() (defined in Object) is to use == to evaluate equals(). However, equals() can be overridden by subclasses of Object (that, is any other class) to provide alternative behavior. That's the difference.

The other difference is that == is defined for primitive types, whereas equals() is only for object references. (However, autoboxing sometimes disguises this difference.)

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • You got there first... – D. Ben Knoble May 01 '15 at 01:34
  • So == was never implemented as a shortcut to Object.equals(). Thank you. I already know the difference in their behaviors (and implementation in `String`), and that Object.equals() can be overridden and == cannot, but why is this feature *not* implemented? – einsteinsci May 02 '15 at 02:08
  • 1
    @einsteinsci - Java does not allow any operator overriding. (A few overrides are built in, such as `+` for strings vs. numeric primitives and `==` for boolean vs. numeric types, but that's it.) The `==` operator is no different from any other operator in this regard. As to why this is, I believe that the language designers were trying to achieve balance expressiveness against complexity. I happen to like this restraint as compared to, for instance, C++. But that's a personal preference and I perfectly well understand why someone might feel differently. – Ted Hopp May 03 '15 at 01:06