Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a custom operator in Java?

Similar to Is it possible to create a new operator in c#?, is it possible to create your own operator for Java? I would initially say no since you can't overload, but then again, String supports + and += (implicitly through StringBuilder at execution time etc).

like image 216
ahodder Avatar asked Apr 23 '12 20:04

ahodder


People also ask

What are custom operators?

Custom operators are also known as advanced operators and allow you to combine two instances with a self-chosen infix, prefix, postfix, or assignment operator.

Is operator overloading is possible in Java?

Your answer Java doesn't supports operator overloading because it's just a choice made by its creators who wanted to keep the language more simple. Every operator has a good meaning with its arithmetic operation it performs. Operator overloading allows you to do something extra than what for it is expected for.

Can you create your own operator in C++?

C++ supports operator overloading, but you are not allowed to create your own operators.


1 Answers

No, Java is not extensible in this way. You can't add operators, and you can't even further overload built-in operators like + - even standard library classes like BigInteger have to use methods such as add() rather than operators such as +.

Scala (another static JVM language) gets around this by using method calls rather than built-in operators, and allowing any characters in method names, so you can define new methods that appear to be operators, i.e.

a + 1

is syntactic sugar for:

a.+(1)
like image 68
DNA Avatar answered Sep 29 '22 17:09

DNA