Operator overloading in Java

Vipul picture Vipul · Nov 6, 2009 · Viewed 210.7k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Nov 6, 2009

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 Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.