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.
You can't do this yourself since Java doesn't permit operator overloading.
With one exception, however. + and += are overloaded for String objects.
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.
Java does not allow operator overloading. The preferred approach is to define a method on your class to perform the action: a.add(b)
instead of a + b
. You can see a summary of the other bits Java left out from C like languages here: http://java.sun.com/docs/white/langenv/Simple.doc2.html
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 /
.