18

Why doesn't Java need operator overloading? Is there any way it can be supported in Java?

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
pure.java
  • 791
  • 2
  • 6
  • 11
  • 17
    Just because it doesn't have a feature doesn't mean it doesn't need it. Java is a simple (relatively) language. Operator overloading is probably one of the most complex features of the languages that allow it (except maybe multiple inheritance) – Falmarri Aug 24 '10 at 18:12
  • In the CLR operator overloading is just syntatic sugar for calling a static method (e.g. op_Add, op_Concatenate, etc). From what I've read the main reason it is hard in C++ is figuring out how to deal with memory. – Jonathan Allen Aug 24 '10 at 18:24
  • See also http://stackoverflow.com/questions/2629501/java-cannot-overload-any-operators-why-closed and http://stackoverflow.com/questions/77718/java-operator-overload – Aaron Novstrup Aug 24 '10 at 18:38
  • @Falmarri Java contains much more complex features than operator overloading (inner classes, autoboxing, generics). In fact, if it weren't for autoboxing, operator overloading could be added in a completely backwards compatible manner. – Antimony Aug 17 '13 at 15:07
  • @Antimony: Please explain how autoboxing is the only thing preventing operator overloading. C++ has the equivalent of autoboxing (implicit conversions) as well as operator overloading. – Falmarri Aug 21 '13 at 20:07
  • @Falmarri the reason is because operations on boxed types would become ambiguous. Do you call a method on them or apply unboxing conversion? Java has worked around compatibility issues in the past (see varargs, generics) but it would be tricky. Anyway, the real "only thing preventing operator overloading" is that the maintainers of Java have no interest in adding it. – Antimony Aug 21 '13 at 21:13
  • @Antimony I think you're confusing what operator overloading is. – Falmarri Aug 21 '13 at 22:37

10 Answers10

15

Java only allows arithmetic operations on elementary numeric types. It's a mixed blessing, because although it's convenient to define operators on other types (like complex numbers, vectors etc), there are always implementation-dependent idiosyncrasies. So operators don't always do what you expect them to do. By avoiding operator overloading, it's more transparent which function is called when. A wise design move in some people's eyes.

Gonen I
  • 5,576
  • 1
  • 29
  • 60
Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
  • 7
    That is almost true, since it defines addition on char and string types. – Jonathan Allen Aug 24 '10 at 18:21
  • 3
    They only forgot BigInteger and BigDecimal :( – Hiro2k Aug 24 '10 at 19:45
  • 3
    @aib: What's worse is they got it wrong. Both C# and Java use + for both addition and concatenation so we get weird type coercion bugs. They very same bugs that Visual Basic solved half a decade before Java was created by splitting them into two operators. – Jonathan Allen Aug 24 '10 at 22:06
  • @Jonathan In Java, char is a numeric type. But the String + hack is a good point. – Antimony Aug 21 '13 at 21:15
  • 6
    It's worth noting that people can always use confusing variable names as well, like xyzzy. The simple fact that people may use a language feature to write obfuscated code should not, by itself, be considered a legitimate reason to avoid that feature, especially when that feature can be used to create *more* readable code when it is used in the right contexts. I find it sad that the only real reason to not use Java for problems whose solution might be most elegantly expressed mathematically (and there's no small number of them) is *just* because the designers don't want operator overloading. – markt1964 Jul 26 '14 at 19:08
  • 9
    From the logic of this answer - method names can be misleading, why allow programmers to give methods a name? Let's just enumerate them with numbers! – Tomáš Zato Apr 29 '15 at 12:16
  • 1
    Whoever decided that Java doesn't need operator overload has obviously never tried to calculate ISS orbital elements with arbitrary precision. I have. Got it right? Yes. Got it readable? Let me think. – Sergei Tachenov Mar 07 '16 at 17:18
11

Java doesn't "need" operator overloading, because no language needs it.

a + b is just "syntactic sugar" for a.Add(b) (actually, some would argue that a.Add(b) is just syntactic sugar for Add(a,b))

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • 15
    According to Java naming conventions, the method `add` should not be capitalized. – Erick Robertson Aug 24 '10 at 18:18
  • 3
    I wasn't speaking of Java specifically, but for languages in general. For example, in Java, you can't have the nonmember function Add(a,b) – James Curran Aug 24 '10 at 18:40
  • 2
    You can have a static method, which is essentially the same. – starblue Aug 24 '10 at 20:30
  • 1
    I thought a.Add(b) was (not exactly) syntactic sugar for call(a.Add,(b)) – Roman A. Taycher Oct 01 '10 at 04:48
  • 63
    Read this: `a.add(b.minus(h).multiply(d.divide(i.add(j))).add(e)).add(c.multiply(f.minus(g.divide(j))))` Now who needs `a+b`! – Shahbaz Nov 06 '11 at 01:59
  • 1
    @Shahbaz `a + ((b - h)*((d/(i + j)) + e) + (c * (f - (g / j)))` and you are saying it is so much simpler ? – firegnom Jul 15 '14 at 09:48
  • 18
    @firegnom, first off, this is how one would normally write that same expression with less parentheses clutter: `a + (b - h) * (d / (i + j)) + e + c * (f - g / j)`, and yes I'm saying that this is so much simpler. For example, I can very quickly see the components that are being added together and what is being multiplied or divided by what. With the `a.op(b)` writing that's quite hard to see. I don't know about you, but I grew up with operator + since primary school, so of course it's much clearer to me. – Shahbaz Jul 15 '14 at 10:26
  • @Shahbaz Excellent example! I could not have said it better. In the end it goes down finding typos and reading formulas. The lack of operator overloading makes Java a terrible language for complex maths. – patrik Oct 25 '16 at 14:45
  • 3
    Aside from syntax and easy readability, operators have priorities in Math. So multiplication has higher priority than adding. `a + b * c` will first do `b * c` than result of it will be added to `a`. Operator overloading makes it easier to handle those without it you have to think about priority order while writing methods. – Muhammed Kadir May 22 '18 at 12:20
7

This related question might help. In short, operator overloading was intentionally avoided when Java was designed because of issues with overloading in C++.

Scala, a newer JVM language, has a syntax that allows method overloading that functions very much like operator overloading, without the limitations of C++ operator overloading. In Scala, it's possible to define a method named +, for example. It's also possible to omit the . operator and parentheses in method calls:

case class A(value: Int) {
   def +(other: A) = new A(value + other.value)
}

scala> new A(1) + new A(3)                                                           
res0: A = A(4)
Community
  • 1
  • 1
Aaron Novstrup
  • 20,967
  • 7
  • 70
  • 108
6

No language needs operator overloading. Some believe that Java would benefit from adding it, but its omission has been publicized as a benefit for so long that adding it is almost certainly politically unacceptable (and it's only since the Oracle buyout that I'd even include the "almost").

The counterpoint generally consists of postulating some meaningless (or even counterintuitive) overload, such as adding together two employees or overloading '+' to do division. While operator overloading in such languages as C++ would allow this, lack of operator overloading in Java does little to prevent or even mitigate the problem. someEmployee.Add(anotherEmployee) is no improvement over someEmployee + anotherEmployee. Likewise, if myLargeInteger.Add(anotherLargeInteger) actually does division instead of addition. At least to me, this line of argument appears thoroughly unconvincing at best.

There is, however, another respect in which omitting operator overloading does (almost certainly) have a real benefit. Its omission keeps the language easier to process, which makes it much easier (and quicker) to develop tools that process the language. Just for an obvious example, refactoring tools for Java are much more numerous and comprehensive than for C++. I doubt that this can or should be credited specifically and solely to support for operator overloading in C++ and its omission in Java. Nonetheless, the general attitude of keeping Java simple (including omission of operator overloading) is undoubtedly a major contributing factor.

The possibility of simplifying parsing by requiring spaces between identifiers and operators (e.g., a+b prohibited, but a + b allowed) has been raised. At least in my opinion, this is unlikely to make any real difference in most cases. The reason is fairly simple: at least in a typical compiler, the parser is preceded by a lexer. The lexer extracts tokens from the input stream and feeds them to the parser. With such a structure, the parser wouldn't see any difference at all between the a+b and a + b. Either way, it would receive exactly three tokens: identifer, +, and identifier.

Requiring the spaces might simplify the lexer a tiny bit--but to the extent it did, it would be completely independent of operator overloading, at least assuming the operator overloading was done like it is in C++, where only existing tokens are used1.

So, if that's not the problem, what is? The problem with operator overloading is that you can't hard-code a parser to know the meaning of an operator. With Java, for some given a = b + c, there are exactly two possibilities: a, b and c are each chosen from a small, limited set of types, and the meaning of that + is baked into the language, or else you have an error. So, a tool that needs to look at b + c and make sense of it can do a very minimal parse to assure that b and c are of types that can be added. If they are, it knows what the addition means, what kind of result it produces, and so on. If they are't, it can underline it in red squiggles (or whatever) to indicate an error.

For C++, things are quite different. For an expression like a = b + c;, b and c could be of almost entirely arbitrary types. The + could be implemented as a member function of b's type, or it could be a free function. In some cases, we might have a number of operator overloads (some of which could be templates) that could carry out that operation, so we need to do overload resolution to determine which one the compiler would actually select based on the types of the parameters (and if some of them are templates, the overload resolution rules get even more complex).

That lets us determine the type of the result from b + c. From there we basically repeat the whole process again to figure out what (if any) overload is used to assign that result to a. It might be built-in, or it might be another operator overload, and there might be multiple possible overloads that could do the job, so we have to do overload resolution again to figure out the right operator to use here.

In short, just figuring out what a = b + c; means in C++ requires nearly an entire compiler front-end. We can do the same in Java with a much smaller subset of a compiler2


  1. I suppose things could be somewhat different if you allowed operator overloading like, for example, ML does, where a more or less arbitrary token can be designated as an operator, and that operator can be given a more or less arbitrary associativity and/or precedence. I believe ML handles this entirely in parsing, not lexing, but if you took this basic concept enough further, I can believe it might start to affect lexing, not just parsing.
  2. Not to mention that most Java tools will use the JDK, which has a complete Java compiler built into the JVM, so tools can normally do most such analysis without dealing directly with parsing and such at all.
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 4
    Try doing extensive work with BigInteger and you may start to come around to the idea that maybe all operator overloading isn't bad. – Jherico Aug 24 '10 at 19:47
  • 1
    I doubt operator overloading is much harder to parse if you force spaces(ie don't allow "a+b" only "a + b") – Roman A. Taycher Oct 01 '10 at 04:51
  • Right lets use regex instead, `Complex c = expression.parse("1+a*b+new Complex(1,1)")` ... or wait, lets build a parser first. It can't be that hard, can it?! – patrik Oct 25 '16 at 14:46
  • @RomanA.Taycher: the parser (as such) isn't normally "aware" of spaces (or lack thereof) at all. Those are handled by the lexer, with no "awareness" of operator overloading at all. The parser just receives tokens from the lexer, so the preceding stream would be `identifier`, `+`, `identifier` whether it included spaces or not. – Jerry Coffin Oct 25 '16 at 15:33
  • @patrik: Sorry, but your comment doesn't make much sense to me. While it's certainly possible to build something like regexes using operator overloading in C++ (e.g., Boost Xpressive) for most typical purposes, it's much more common to do it at run-time (e.g., Boost regex, `std::regex`, etc.) Each has good and bad points, but they both work. – Jerry Coffin Oct 25 '16 at 17:16
  • @JerryCoffin Ok sorry for the tone in the comment. I guess I felt you sounded selfrighteous in the post with the "On language needs operator". While I understand your issues, the does not justify that all people working with maths should either build an interpreter for let us say, complex arithmetics or deal with the consequences on not doing so. Operator overloading would allow much easier functionality for maths and all the developer would have to do is to write an operator overload. – patrik Oct 26 '16 at 06:38
  • @patrik: To me, the arguments in favor of Java sound a lot like: "the weather here is decent, and you can choose from many bridges to sleep under." Java IDEs add in: "and there's a really good soup kitchen." Me, I really *like* being able to take a hot shower first thing in the morning, but if the question is whether you truly *need* a house to survive, the answer is clearly "no". Java advocates are like people preaching the "virtues" of living under a bridge, but that doesn't change the fact that it *is* possible to do so. – Jerry Coffin Oct 26 '16 at 13:38
4

java-oo compiler plugin can add Operator Overloading support in Java.

mart
  • 2,537
  • 1
  • 15
  • 13
2

It's not that java doesn't "need" operator overloading, it's just a choice made by its creators who wanted to keep the language more simple.

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
2

Java does not support operator overloading by programmers. This is not the same as stating that Java does not need operator overloading.

Operator overloading is syntactic sugar to express an operation using (arithmetic) symbols. For obvious reasons, the designers of the Java programming language chose to omit support for operator overloading in the language. This declaration can be found in the Java Language Environment whitepaper:

There are no means provided by which programmers can overload the standard arithmetic operators. Once again, the effects of operator overloading can be just as easily achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables. Eliminating operator overloading leads to great simplification of code.

In my personal opinion, that is a wise decision. Consider the following piece of code:

String b = "b";
String c = "c";
String a = b + c;

Now, it is fairly evident that b and c are concatenated to yield a. But when one consider the following snippet written using a hypothetical language that supports operator overloading, it is fairly evident that using operator overloading does not make for readable code.

Person b = new Person("B");
Person c = new Person("C");
Person a = b + c;

In order to understand the result of the above operation, one must view the implementation of the overloaded addition operator for the Person class. Surely, that makes for a tedious debugging session, and the code is better implemented as:

Person b = new Person("B");
Person c = new Person("C");
Person a = b.copyAttributesFrom(c);
Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
  • 12
    "[...] it is fairly evident that using operator overloading does not make for readable code." I wonder what kind of a language we'd be left with if we removed every feature that could be abused. – Aaron Novstrup Aug 24 '10 at 18:30
  • 1
    @anovstrup, I guess that would be a somewhat verbose yet understandable language with scope for committing fewer mistakes. I prefer languages that do not allow me to do this - #define private public (or their variants thereof). – Vineet Reynolds Aug 24 '10 at 18:36
  • @Vineet: Neither C nor C++ allows that, IIRC. I think it's undefined behavior under both standards. – bcat Aug 24 '10 at 18:44
  • 4
    I've always hated the logic that "because a bad programmer can use this functionality to write bad code, this functionality is bad". There are plenty of cases where operators in the code would be far clearer than method names. Knowing when to use operator overload and when not to is just one sign of a better programmer. You could just as easily say "being able to have two methods with the same name is bad, because someone might name all their methods the same name even if they do something different". – RHSeeger Aug 24 '10 at 18:56
  • @bcat, well undefined behavior under standards have never prevented people from getting clever with macros or other aspects of languages that were originally introduced to help programmers write better code. – Vineet Reynolds Aug 24 '10 at 19:03
  • 3
    @downvoter While I disagree with Vineet (I prefer a language that enables the good programmer to express his intent efficiently to one that coddles the bad programmer), I don't think this answer deserves a downvote. Whether we agree with the Java designers or not, this argument *is* one of the reasons that Java does not support operator overloading. – Aaron Novstrup Aug 24 '10 at 19:06
  • @RHSeeger, knowing when to use operator overload is good in hindsight. Not when you have to debug code written by a self-aggrandizing programmer. Writing readable code implies that you respect the time others spend on reading, debugging and eventually using your code. – Vineet Reynolds Aug 24 '10 at 19:07
  • 1
    @Vineet, Bad programmers will write bad code in any language. Sure, some language features make it easier or harder, but those same language features can have the exact opposite effect for good programmers (making code clearer used by a good programmer vs uglier used by a bad programmer). Just because people are injured in car accidents doesn't mean we should all be riding horses. – RHSeeger Aug 24 '10 at 20:16
  • @RHSeeger, well, last time I checked people wanting safe cars chose ones with air bags and all the other safety features. We don't need to ride horses, but the extra safety is worth it :-) – Vineet Reynolds Aug 24 '10 at 20:43
1

OK Well... we have a very discussed and common issue. Today, in software industry, there are, mainly, two different types of languages:

  • Low level languages
  • High level languages

This distinction was useful about 10 years before now, the situation, at present, is a bit different. Today we talk about business-ready applications. Business models are some particular models where programs need to meet many requirements. They are so complex and so strict that coding an application with a language like c or c++ would be very time-spending. For this reason hybrid languages where invented.

We commonly know two types of languages:

  • Compiled
  • Interpreted

Well, today there is another one:

  • Compiled/Interpreted: in one word: MANAGED.

Managed languages are languages that are compiled in order to produce another code, different from the original one, but much more complex to handle. This INTERMEDIATE LANGUAGE is then INTERPETED by a program that runs the final program.

It is the common dynamics we came knowing from Java... It is a winning approach for business-ready applications. Well, now going to your question...

Operator overloading is a matter that concerns also multiple inheritance and other advanced characteristics of low level languages. Java, as well as C#, Python and so on, is a managed language, made to be easy to write and useful for building complex applications in very few time. If we included operator overloading in Java, the language would become more complex and difficult to handle.

If you program in C++ you sure understand that operator overloading is a very very very delicate matter because it can lead to very complex situations and sometimes compiler might refuse to compile because of conflicts and so on... Introducing operator overloading is to be done carefully. IT IS POWERFUL, but we pay this power with an incredibly big load of problems to handle.

OKOK IT IS TRUE, you might tell me: "HEY, But C# uses operator overloading... What the hell are you telling me? why c# supports them and Java not?". Well, this is the answer. C#, yes, implements operator overloading, but it is not like C++. There are many operator that cannot be overloaded in c# like "new" or many others that you can overload in c++... So C# supports operator overloading, but in a much lower level than c++ or other languages that fully supports it. But this is not a good answer to the earlier question... The real answer is that C# is more complex than Java. This is a pro but also a con. It is a matter of deciding where to place the language: high level, higher level, very high level? Well, Java does not support op overloading because it wants to be fast and easy to manage and use. When introducing op overloading, a language must also carry a large amount of problems caused by this new functionality.

It is exactly like questioning: "Why does Java not support multiple inheritance?" Because it is tremendously complex to manage. Think about it... IT WOULD BE IMPOSSIBLE for a managed language to support multiple inheritance... No common class tree, no object class as a common base class for all classes, no possibility of upcasting (safely) and many problems to handle, manage, foresee, keep in count...

Java wants to be simple. Even if I believe that future implementations of this language will result in supporting op overloading, you will see that the overloading dynamics will involve a fewer set of all the possibilities you have about overloading in C++.

Many others, here, also told you that overloading is useless. Well I belong to those ones who think this is not true. Well, if you think this way (op overloading is useless), then also many other features of managed languages are useless too. Think about interfaces, classes and so on, you really do not need them. You can use abstract classes for interface implementations... Let's look at c#... so many sugar syntax, LINQ and so on, they are not really necessary, BUT THEY FASTEN YOUR WORK... Well, in managed languages everything that fasten a development process is welcome and does not imply uselessness. If you think that such features are not useful than the entire language itself would be useless and we all would come back programming complex applications in c++, ada, etc. The added value of managed languages is to be measured right on this elements.

Op overloading is a very useful feature, it could be implemented in languages like Java, and this would change the language structure and purposes, it would be a good thing but a bad thing too, just a matter of tastes. But today, Java is simpler than C# even for this reason, because Java does not supports op overloading.

I know, maybe I was a little long, but hope it helps. Bye

Andry
  • 16,172
  • 27
  • 138
  • 246
  • 1
    I might not agree with everything in this post, but at least you really thought it through, unlike some others who posted an answer. So have my +1 :) – Tomáš Zato Apr 29 '15 at 12:40
0

Java doesn't support operator overloading (one reference is the Wikipedia Operator Overloading page). This was a design decision by Java's creators to avoid perceived problems seen with operator overloading in other languages (especially C++).

GreenMatt
  • 18,244
  • 7
  • 53
  • 79
0

Check Java Features Removed from C and C++ p 2.2.7 No More Operator Overloading.

There are no means provided by which programmers can overload the standard arithmetic operators. Once again, the effects of operator overloading can be just as easily achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables. Eliminating operator overloading leads to great simplification of code.

Incognito
  • 16,567
  • 9
  • 52
  • 74