Operator overloading in Java

Please can you tell me if it is possible to overload operators in Java? If it is used anywhere in Java could you please tell me about it.


No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.

For a Java-like (and JVM-based) language which does support operator overloading, you could look at Groovy. Alternatively, you might find luck with a Java compiler plugin solution.


Operator overloading is used in Java for the concatenation of the String type:

String concat = "one" + "two";

However, you cannot define your own operator overloads.


In addition to all the people pointing out that + is overloaded for Strings, - is also overloaded for both floating point and integer operations, as are * and / .

[edit] % is also overloaded for floating point, which can be a bit of a surprise for those with a C or C++ background.

链接地址: http://www.djcxy.com/p/73094.html

上一篇: 如何在Ruby中使用条件运算符(?:)?

下一篇: 运算符在Java中重载