209

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.

teabot
  • 15,358
  • 11
  • 64
  • 79
Vipul
  • 2,637
  • 6
  • 25
  • 28
  • Possible duplicate of [Why doesn't Java offer operator overloading?](https://stackoverflow.com/questions/77718/why-doesnt-java-offer-operator-overloading) – Anderson Green Sep 23 '17 at 21:22

11 Answers11

263

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.

Eerik Sven Puudist
  • 2,098
  • 2
  • 23
  • 42
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 4
    You are saying we cant create wrapper in java? Such as SmallInteger like Integer? – huseyin tugrul buyukisik Sep 12 '12 at 10:58
  • 4
    @tuğrulbüyükışık: There are already wrappers for all the existing primitive types - but if you wanted to create your own new wrapper type, you wouldn't be able to make it behave like the other ones, as they have specific support in the language. – Jon Skeet Sep 12 '12 at 12:29
  • 1
    thanks, i googled about it and couldnt find. I wanted to know if i could make a complex variable composed of two primitives (a double and an int--->good precision+good range) – huseyin tugrul buyukisik Sep 12 '12 at 12:45
  • 1
    It would be cool if the Java team would add it in Java 8 or something – Shaun Wild May 11 '13 at 13:05
  • @JonSkeet I would love to hear your take on why they didn't add things like operator overloading, delegates etc to java? I personally don't like operator overloading, since code is less readable, and delegates somehow break OOP principle. But I want to hear your scholarly opinion, would you please? – Aqeel Ashiq May 15 '13 at 08:00
  • 48
    @djaqeel: Operator overloading makes the code less readable *when used badly*. When used well, it can greatly enhance readability IMO. Look at code which uses `BigInteger` in Java, then look at similar code using `BigInteger` in C# using operators. I don't see how delegates break OOP principles - you need to be much more precise than that in your objections. I don't know the details of why the Java designers didn't include various features, but I suspect there's a mixture of resource pressure and a desire to keep the language small and relatively simple. – Jon Skeet May 15 '13 at 08:47
  • 8
    I know this is late, but an example is worth a thousand arguments. Given `m0` as a `Matrix` and `v0`, `v1`, `v2`, `v3`, and `v4` as `Vector`s, simply compare how long it takes you to *correctly* interpret the following mathematical expression `m0.transpose().mult(v0.add(v1.mult(v2)).cross(v3)).sub(v4);`. Had support for operator overloading been included, it could've been written as `m0.transpose() * (v0 + v1 * v2).cross(v3) - v4;`. – code_dredd Oct 13 '17 at 21:32
38

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.

teabot
  • 15,358
  • 11
  • 64
  • 79
26

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350
21

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: Features Removed from C and C++

rob
  • 1,154
  • 2
  • 12
  • 18
  • 2
    The important thing is the design goal of making Java source files context independent. Trying to read very large (MLOC), macro heavy C programs has a very long learning curve. A comparable ( or larger) Java program is no harder to dip into than a small Java program. As Gosling said: A language for blue collar programmers to work in. [And anyone who thinks boilerplate verbosity is detrimental should read about chunking in expert cognition.] – Tim Williscroft Sep 12 '11 at 00:53
  • 3
    Thanks to oracle, none of the java.sun.com links work. Can you please give the updated link, if possible? – Aqeel Ashiq Nov 01 '13 at 13:20
19

As many others have answered: Java doesn't support user-defined operator overloading.

Maybe this is off-topic, but I want to comment on some things I read in some answers.

About readability.
Compare:

  1. c = a + b
  2. c = a.add(b)

Look again!
Which one is more readable?

A programming language that allows the creation of user-defined types, should allow them to act in the same way as the built-in types (or primitive types).

So Java breaks a fundamental principle of Generic Programming:
We should be able to interchange objects of built-in types with objects of user-defined types.
(You may be wondering: "Did he say 'objects of built-in'?". Yes, see here.)

About String concatenation:

Mathematicians use the symbol + for commutative operations on sets.
So we can be sure that a + b = b + a.
String concatenation (in most programming languages) doesn't respect this common mathematical notation.

a := "hello";
b := "world";
c := (a + b = b + a);

or in Java:

String a = "hello";
String b = "world";
boolean c = (a + b).equals(b + a);

Extra:
Notice how in Java equality and identity are confused. The == (equality) symbol means:
a. Equality for primitive types.
b. Identity-check for user-defined types, therefore, we are forced to use the function equals() for equality.
But... What has this to do with operator overloading?
If the language allows the operator overloading the user could give the proper meaning to the equality operator.

Abhinav
  • 530
  • 8
  • 21
  • The symbol `==` is used for equality in Java, as in C and C++. This has nothing to do with operator overloading. – Hot Licks Oct 11 '14 at 00:01
  • 3
    The operator==, in Java only means Equality for primitive types. For user-defined types means Identity. In C++ the semantic is defined by the user, but should preserv the built-in semantics, equality. String a = "hello"; String b = "hello"; boolean c = (a == b); – Fernando Pelliccioni Oct 11 '14 at 01:23
  • 4
    So what you said in your first comment is wrong. Right? Please, tell me how to test equality and identity on user-defined types in C. You are right, my comment about equality is OT, but I clarified that (see the "extras"). The fact that I have not created a programming language does not mean I can not criticize an existing one. I am sorry if you've seen the criticism as a religious war. – Fernando Pelliccioni Oct 11 '14 at 07:00
  • 3
    Putting long things short: java sucks. – Kolya Ivankov Oct 18 '17 at 13:39
17

You can't do this yourself since Java doesn't permit operator overloading.

With one exception, however. + and += are overloaded for String objects.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 9
    There are many other examples of operator overloading in Java. For instance `&`, `|`, and `^` are overload for `boolean` and integral types. And indeed, the arithmetical and relational operators are overloaded for various numeric types. (Of course, the overloads' semantics are much closer ...) – Stephen C Nov 13 '13 at 10:51
12

One can try Java Operator Overloading. It has its own limitations, but it worth trying if you really want to use operator overloading.

Alexander Mironov
  • 3,095
  • 26
  • 28
8

Just use Xtend along with your Java code. It supports Operator Overloading:

    package com.example;

@SuppressWarnings("all")
public class Test {
  protected int wrapped;

  public Test(final int value) {
    this.wrapped = value;
  }

  public int operator_plus(final Test e2) {
    return (this.wrapped + e2.wrapped);
  }
}

package com.example

class Test2 {

    new() {
        val t1 = new Test(3)
        val t2 = new Test(5)
        val t3 = t1 + t2
    }

}

On the official website, there is a list of the methods to implement for each operator !

Aurelien B
  • 148
  • 1
  • 8
5

Or, you can make Java Groovy and just overload these functions to achieve what you want

//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...

class Fish {
    def leftShift(Fish fish) {
        print "You just << (left shifted) some fish "
    }
}


def fish = new Fish()
def fish2 = new Fish()

fish << fish2

Who doesnt want to be/use groovy? :D

No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
alknows
  • 1,972
  • 3
  • 22
  • 26
2

Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.

We can take +(plus) for example:

int a = 2 + 4;
string = "hello" + "world";

Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
0

Java does not support this out of box but there is a solution in a form of a compiler plugin and it allows you to do that.

See this article about id on https://foojay.io/today/operator-overloading-in-java/

Plugin is http://manifold.systems/

Adam Ostrožlík
  • 1,256
  • 1
  • 10
  • 16