What is the difference in the evaluation rule of an operator and a method in Java?
Operators can be seen as syntactic sugar for
static Foo Plus (Foo right, Foo left)
{
// do stuff
return output;
}
It's just more convinient to write right + left instead of Class.Plus(right, left).
Femaref's answer is pretty good; I'd like to expand on it.
Operators are (usually) hard-wired into the language: Stuff like +, -, * and / are usually directly translated by the compiler into machine language (if that's the underlying mechanism for that language system) without the need to explicitly call a method in a library. This is how it is/was in C, for instance. If those operators weren't defined in the language, you'd have to code plus(2,2) instead of 2 + 2.
Operators defined in the language come with the benefit of built-in priority. * and / usually have higher priority than + and -, so you can write 3 * 3 + 4 * 4 and get 25, not 52 or 84 that you'd get without such priorization or different priorities.
The line becomes a little grey when operators are recognized by the compiler but still delegated to a library. Complex numbers in FORTRAN may be an example: Often the compiler will not bother to directly compile complex operations into machine code but will generate machine code to call a library.
Most people think only of the arithmetic operators, like +, - and so forth. But you could also consider square brackets ( [ ] ) an operator for array indexing, for example.
Some languages let you overload their operators, so you can substitute a call to a method for whatever the operator normally does.
Most languages don't let you define your own operators that support the same mechanisms as the built-in ones. Scala is an exception here; you can define a +++ operator if you like and have it hook up to a method you provide. Some people think operator overloading makes code harder to understand, so the jury is still out about whether this is a good idea.
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