Thursday, August 5, 2021

Why Java does not support Operator overloading? Answer

Unlike C++, Java doesn't support operator overloading. Java doesn't provide freedom to programmers, to overload the standard arithmetic operators e.g. +, -, * and / etc. If you have worked previously in C++, then you know that Java has left a lot of features supported in C++ e.g.  Java doesn't support multiple inheritances, no pointers in Java, and no pass-by-reference in Java. Rarely is this question asked in Java interviews, to check how a programmer thinks about certain features, which are not supported in Java. 

Another similar question is regarding Java being pass by reference, which mostly appears as, whether Java is pass by value or reference.




4 Reasons Why Java doesn't support Operator Overloading

Though I don't know the real reason behind it, I think the following observation makes sense on, why Operator overloading is not supported in Java.


1) Simplicity and Cleanliness

Why operator overloading is not supported in JavaThe simple and clear design was one of the goals of Java designers. They, just don't want to replicate the language, but wanted to have a clear, truly object-oriented language. Adding Operator overloading would have definitely made the design more complex than without it, and it might have lead to the more complex compiler or slows the JVM because it needs to do extra work to identify the actual meaning of operators and reduce the opportunity to optimize the language by guarantee behavior of operators in Java.



2) Avoid Programming Errors

Java doesn't allow user-defined operator overloading, because if you allow a programmer to do operator overloading, they will come up with multiple meanings for the same operator, which will make the learning curve of any developer hard and things more confusing and messy.

Its been observed that there is an increase in programming errors when language supports operator overloading, which in turn increases e development and delivery time.

Since Java and JVM have taken most of the developer's responsibility,  in memory management by providing garbage collector, it doesn't really make sense to left this feature to pollute the code, and as a loop hole for programming errors.



3) JVM Complexity

From the JVM perspective, supporting operator overloading is more difficult, and if the same thing can be achieved, by using method overloading in a more intuitive and clean way, it does make sense to not support operator overloading in Java.

A complex JVM, may result in a slower JVM, than a relatively simpler JVM, and reduce the opportunity of optimization by taking out guaranteed behavior of operators in Java.



4) Easy Development of Tools

This is an additional benefit of not supporting operator overloading in Java. The omission of operator overloading has kept the language easier to handle and process, which in turn makes it easier to develop the tools, that process the language e.g. IDE or re-factoring tool. Re-factoring tools in Java are far better than C++.


In conclusion, many things, which can be achieved by operator overloading, can also be achieved using method overloading using more intuitive and easy way and that might be the reason java designer thought that supporting operator overloading will not be a big benefit for language, but in fact, only Java designer can answer real motivation of, why Java doesn't support operator overloading, like some other questions as Why Java doesn't support multiple inheritances or Why String is immutable in Java.

22 comments:

  1. I had a long and detailed comment rebutting you point by point, but Blogspot ate it.

    So to be short and sweet, everything you said about the JVM is wrong. The JVM doesn't and won't do overloading, function or operator, even when your program uses overloading. That's the compiler's job. Operator overloading will have precisely zero impact on the JVM.

    ReplyDelete
    Replies
    1. The standard idiom for using the wait method synchronized (obj) { while (condition does not hold) obj.wait(); // (Releases lock, and reacquires on wakeup) ... // Perform action appropriate to condition }

      Delete
  2. Ahh :(. important information lost. @Anonymous I value your thought and I may be wrong but would be great if you could put some references. In my opinion if you are going to implement operator overloading It could vary based on Object (and not Type) and since Object is only available at run-time it should involve JVM to resolve that.Once again thanks for your valuable comment and time, I am ready to correct if I come across any reference.

    ReplyDelete
  3. I am not the same Anonymous, but you might want to check this pseudo code:

    AnyObject foo;

    Something1 = foo.bar(1);
    Something2 = foo.bar("asd");
    Something3 = foo + 1;
    Something4 = foo + "asd";

    The difference between a polymorph and overloaded call to bar() is identical to an overloaded operator+

    Whether the functioname is "bar" or "operator+" makes no difference in neither runtime nor compiletime.

    ReplyDelete
  4. That's not true.

    1. Java is not object oriented (int and float are not objects)
    2. You could also write a function add() to multiply as you can overload operator + to do the multiplication. The name of the function does not help to avoid such errors.
    3. For JVM it doesn't matter, operators are just normal functions.

    The version with operator overloading looks much clearer

    Let's compare two numbers...

    price < 0

    price.compareTo(BigDecimal.ZERO) == -1

    Let's add and multiply...

    (a + b) * c

    (a.add(b)).multiply(c)

    ReplyDelete
  5. Really? Will it be so bad on jvm? are we running our apps on P1 processors?
    I think operator overloading makes your code more intuitive and if few programmers makes programming error in using it then they should better write some unit tests. I pity on such developers, how they gonna learn ruby or groovy?

    ReplyDelete
  6. I agree with Anonymous. Operator overloading could be implemented in compile time: the bytecode generated would be just a method call - for instance, a+b translates to a.plus(b)

    ReplyDelete
  7. java does not support operator overloading , because it is a *stupid* decision made by its inventor. Everything that is in java, does not have to be rational.
    operator overloading support does not have any impact on jvm, because it is not a runtime feature. Multiple meanings for the same operator is not a bad thing, because using function overloading one could also assigns multiple meanings to the same function name, hence java should not support functions/methods at all, everything should be in just a sequence.
    one could also put intentional for loops and conditionals at many programmings places and produce errors, hence as per you it will be logical to remove if and for loops from the language.
    JUST FACE IT. Designers of java made some good decisions about language, and some bad decisions about the language. And we need not justify the bad decisions till date.

    ReplyDelete
  8. Hello, another anonymous here.

    Java was REALLY basic when first out. It had no generics, no enums, it still have no lambda expressions. You can only start to make using of strings in swiches with java 7.

    In fact many things that have been already added or that will be here with java 8 were before seen as bad by many similar argument than yours.

    Hard to optimize, prone to errors...

    The truth for operator overloading is that it's easier on the eyes to write:

    (A * B) + C than (A.multiply(B)).plus(C).

    So in C++,C#, scala and many other languages all matrix libraries can provide operator for matrixes. Java can't.

    Yes the design is simpler, and has less complexity but there are real cases for operator overloading. The main case is it make code more explicit, more expressive, and thus easier to maintain. There a reason you can use operator on ints or double (so with overloading already). Because you need operators !

    Yes you can do weird things with operator overloading, as with templates, lambda expressions... But theses features are just added in new versions of JAVA anyway. And java 1.0 code was hugly... Less clear, needed cast everywhere ...

    Nothing perfect.

    ReplyDelete
  9. The writer of this article doesn't understand how the JVM works, when he says operator overloading would result in a slower JVM. At best, it would result in slower compilation of code, but it could never result in slower run-time code. The run-time code would still be put into regular bytecode, and it would run at the exact same speed. When operators are overloaded in other languages and then compiled, the language does the job of assigning the operators to methods at compilation so that run-time is unaffected.

    Furthermore, the arguments that operators lead to more confusing code is absolutely bunk. Java already supports operator overloading in very limited instances. Strings for example have the "+" operator. You can concatenate strings without having to do something convoluted like SomeString.add(SomeOtherString). No one complains about this.

    For the person who said "The real advantage come when Java programmers never have to think about whether the + operator adds two objects or appends one object to another." is ridiculous. If I created an "add" method for a class of mine, and that "add" method accepted an object of the same class, how would you know if I wasn't just taking the data from the second object and pushing it onto the first object or if I was creating an entirely new object? You'd have to look at the code or the documentation, wouldn't you? The same goes for operator overloading. You'd have to become familiar with the code. It's not like because there aren't operators being overloaded, then suddenly everything is magically intuitive and easy to understand.

    ReplyDelete
  10. @D, I appreciate your comment and thought but not completely agree. Operator overloading can be even implement using method overloading or overriding and if it does on object level it has to go runtime because object only available in runtime. it all depends upon implementation , though a compiler dependent method is more appropriate and its just an observation that it's a confusing feature though it still supported by many language. When Java was designed , in my opinion designer thought to remove certain feature not just because technical difficulty but as choice and previous experience.Anyway thanks for your comment.

    ReplyDelete
  11. Nobody seems to have noticed an obvious (and serious) mistake in the very introduction to the post:

    "Java doesn't support multiple inheritance, no pointers in Java and no pass by reference in java."

    Wrong, there are pointers in Java, and to be even more precise - only pointers exist in Java (the only exception to that rule are primitive types). The fact that you don't have to use * operator like in C++ doesn't mean that the pointers are gone.

    I'm afraid you don't have deep knowledge about things that your writing about.

    ReplyDelete
  12. Another anonymous here...

    I agree with what killy said. Java has pointers. What we call handle in Java is basically a pointer. Try to recollect 'this' pointer in Java. Because of 'this' pointer, Java is object based programming language.

    What Java doesn't PROVIDE is POINTER ARITHMETIC

    ReplyDelete
  13. @Anonymous, Thanks for your comment. you can call reference as pointer and I like your precise answer. you can not get address of pointer or get a reference by accessing memory address.

    ReplyDelete
  14. I agree java doesn't support operator overloading.But lets say an example of (+) operator. + is used for arithmatic addition and also it is used as a concatenation operator for String.Doesn't it mean operator overloading?

    ReplyDelete
  15. @Partha: Yes, the String concatenation is the only one operator overloading in Java and it clearly shows how wrong it can be. Plus is an associative operator while String concatenation is not. Further, the fact that String concatenation has the same operator precedence than arithmetic plus causes a lot of problems. A dedicated concatenation operator different than all other operators would have been the better choice. However, this does not prove that operator overloading is always evil. There is nothing wrong with providing arithmetic operators for arithmetic classes. But examples like abusing the shift-operator for I/O stream operations in C++ show that even the experts tend to abuse overloading if it exists…

    ReplyDelete
  16. I dislike stupid comments by people who technically worship C++, we don't worship Java .. it's just a programming language we aim to keep simple for everyone

    It become so stupid, as comments get to suggest that C++ is actually computer science, or C++ invented Object-Oriented patterns, or that Java is not object-oriented because it does not provide operator overloading

    And we're not going to go into discussing any of these points, because engineers already know the answers well .. but it's a waste of time if the other person is not willing to listen with reason

    We certainly don't want to morph the language, that's not the aim .. then what is the aim of having a language, or a standard .. just go enjoy C++14, as they seem to standardize stupid features because why not (like having the single comma number separator that's just for readability)

    ReplyDelete
  17. Actually, not supporting operators violates almost all items you mentioned in your blog article.

    1) Simplicity and Cleanliness
    VIOLATED: Not having operator overloading violates this because it makes it mandatory to use some weird method that is used instead of an operator which is intuitive. At the same time, this makes it UNCLEAN. equals() vs "==" is more clean? More simple? Seriously?

    2) Avoid Programming Errors
    VIOLATED: Because of #1. Programmers first go for "==", and then when they see an error they realise "ah crap, that is a user-defined type, i must use some method to test equality.

    3) JVM Complexity
    WHAT? :) There is no complexity required by JVM involved here. JVM has everything needed for operator overloading.

    4) Easy Development of Tools
    This is basically a job for the Java parser. It already parses operators anyway (for plain-old data), so there is almost no overhead.

    Similar arguments were against lambdas in Java, but they became part of Java eventually. Same will most likely be with the operator overloading. It is also backwards compatible - those masochists who prefer having zillion, non-standardized (someone will have equals() somebody else will have same(), or isEqual() or whatever), methods - go ahead, let them have it (yeah, those who need Comparable or similar will have to have standardized names, thank God for that at least), but let us who want modern language to have modern language features. :)

    ReplyDelete
  18. After Reading all valuable comments of all Technical geeks. Can any body let me know the final answer of the question" Why java does not support operator overloading"

    ReplyDelete
  19. Dear java support Operator overloading. Let's see example...
    20+30=50
    'ab'+'cd'=abcd
    then how can u telling in not provide operator overloading.

    ReplyDelete
  20. @Bhupendra, String is special, what we are discussing here to overload any operator programatically, which is not supported by Java unlike C++.

    ReplyDelete
  21. Can anybody answer the actual question here?

    ReplyDelete