Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 4905919
Votes 219
Synopsis RFE: Operator overloading
Category java:specification
Reported Against 1.4.2 , tiger-beta2
Release Fixed
State 6-Fix Understood, request for enhancement
Priority: 4-Low
Related Bugs 6349553 , 6454574 , 4909261
Submit Date 13-AUG-2003
Description


A DESCRIPTION OF THE REQUEST :
There is an intensive discussion about adding operator overloading to the java language

Please also see:

http://developer.java.sun.com/developer/bugParade/bugs/4087427.html

JUSTIFICATION :
This post is made to give the people the chance to discuss and vote.
(Incident Review ID: 199033) 
======================================================================




A DESCRIPTION OF THE REQUEST :
Even though there's a sort of JVM operator overloading (see toString or the == in enum), this language feature is still missing as a general language extension.


JUSTIFICATION :
Operator overloading can be avoided using functions, of course, but there are cases where the code become more readable, simpler and self-documenting.
I do know all the pros and cons about this, but as I heard similar things for some of the new great improvement on the way with 1.5, I don't see why the operator overloading has been left apart.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The behaviour would be much like the normal c++ behaviour.
ACTUAL -
No behaviour can be described as it's a non permitted syntax expression.

---------- BEGIN SOURCE ----------
public class MultiTierApp {
...
}

public class Tier1 implements Tier {
}

public class Tier2 implements Tier {
}

MultiTierApp mta = (new Tier1) + (new Tier2);
---------- END SOURCE ----------
(Review ID: 296755)
======================================================================
Posted Date : 2006-05-11 18:29:58.0
Work Around
N/A
Evaluation
I have always objected to this, but I'll leave it os people can vote.

  xxxxx@xxxxx   2003-08-20
Comments
  
  Include a link with my name & email   

Submitted On 12-DEC-2003
M.R.Atkinson
The main objection to operator overloading is that it is
easy to create code that is harder to read, debug and that
does not obey the semantics of the operators.

If operator overloading were only allowed in java.* and
javax.* classes then the above objection would be overcome,
while at the same time allowing libaraies (e.g. for interval
arithmatic) to use the operator overloading.


Submitted On 10-FEB-2004
YoGee
"... but I'll leave it so people can vote" - That's great, but 
how do we vote against it?


Submitted On 15-FEB-2004
tschodt
I agree with YoGee: "... how do we vote against it?"




Submitted On 15-FEB-2004
crackers
Operator overloading is one of the most vile, confusing, and
consistently mis-used facilities of C++. It is a maintenance
nightmare. Since there is no way to vote against (at this
point), I'll just leave this comment instead.


Submitted On 15-FEB-2004
sjasja
One vote against here too.

Existing practice amply evidences more abuse than use.

Limitied usability - please consult any
above-elementary-school level math / physics / chemistry
book to see the range of operators needed to express equations.

(Or can I vote NAY twice since I have two empty votes?)


Submitted On 16-FEB-2004
silk.m
against ...


Submitted On 16-FEB-2004
mlk
Against. 


Submitted On 16-FEB-2004
jverd
Against, but...

As discussed in

http://forum.java.sun.com/thread.jsp?
forum=54&thread=489919

beginning around post #38 and continuing for the next 
several posts, if a compromise could be found that 
gave some healthy fraction of the power of operator 
overloading but eliminated most of the dangers and 
fugliness that acompany it in C++, I'd be all for it.

Note that I can't quantify exactly what that means, but if 
somebody better qualified can, then great!

My objection is in line with the general sentiments 
against. It doesn't add functionality, just notational 
convenience.

While there is value in being able to express one's 
intent concisely, the potential for abuse and confusion 
outweighs the potential gains of full-blown C++ style 
overloading.


Submitted On 16-FEB-2004
jschell
Another vote against it


Submitted On 17-FEB-2004
dcminter
If a proposal more in the spirit of Java's general
philosophy can be found, then that would be worth
reconsidering - however, as for C++ style operator
overloading ? Against.


Submitted On 17-FEB-2004
CliffNotes
Let me put a vote in favor. It wouldn't require a radical 
change to the language. You could simply have an 
interface, say "Operable", which consisted of 
appropriate methods to implement, 
say "equals", "plus", "minus", "times", "dividedBy", etc. 
and any class that implemented that interface could be 
used with the operators corresponding to the methods 
implemented. That way you could avoid the ugly C++ 
syntax and have something elegant that fit fight in with 
the language.


Submitted On 17-FEB-2004
Pete_Kirkham
Apart from some very simple cases, in the absence of stack
allocation of objects, the mechanisms by which matrix and
vector math operators are implemented in any intensive
application require a choice between mutating methods ‘add y
to x’ and functional methods ‘the result of x plus y’.
Simple operator overloading does not supply this subtlety.

For numerically intensive work, I use a simple pre-processor
to generate Java source from s-expressions. There may be a
case for a pre-processor for Java numerical applications
using a more Java-like syntax, that also allows sufficient
control of the expansion of operators to give an efficient
program.

A general facility for operator overloading doesn’t seem to
be enough for numerical applications. If you read Usenet or
Java forums, the most frequently occurring (though not
necessarily the most severe) case of inefficiency in Java
programs is the use of ‘+’ for string concatenation. The
only way to get efficient string concatenation in an
iterative Java program is to manually circumvent the ‘+’
operator. In numerical applications, this effect is likely
to be as important. I don’t believe that making it easier
for people to type in inefficient programs is an improvement
to Java’s numerical computing capability.

Pete Kirkham, Technical Computing, BAE SYSTEMS


Submitted On 17-FEB-2004
YATArchivist
I'm against operator overloading. AFAICT, the only operators which would 
really benefit from being overloadable are + and -, and possibly * 
(although this would only really be useful for matrices). Allowing people to 
change the meaning of + would break existing toString methods.


Submitted On 19-FEB-2004
lucretius
IMHO the crucial question is: why are method calls involving 
symbols (+, * etc.) considered 'confusing' or 'easily abused' 
whereas method calls with names (get, add etc.) are not.

I can see two reasons:
1. Symbols like + and * are very frequently used in code, with 
specific (usually arithmetic) meanings. If you can use them as 
method names in your own classes, there is a strong implication 
that they will have similar behaviour to the arithmetic behaviour.

2. Symbols are more abstract than words. This means people 
more likely to assign 'expected' behaviour to a method 
called 'add' than to a method called '+'. ('plus' would be even 
better.) For instance, I suspect people would have felt less 
comfortable using a method called 'plus' to concatenate Strings 
than a method called '+', which is (in effect) what we have. This 
is because 'plus' is more obviously arithmetic, with the 
implication that there is a corresponding 'minus' method that 
undoes a 'plus'.

So I think however you define a method called '+', it needs to 
carrry a strong incentive for the programmer to define a method 
which has expected properties. I can see several ways to do this:

Solution 1. Whatever the syntax for operator overloading, Java 
could stipulate a *contract* for basic operators such as +, -, *, / . 
The contract could be rings or fields, e.g. if you define a + 
operator, you must also define a - operator (and maybe an == 
operator) such that always (a + b - b).equals(a), or a + b - b == 
a. This contract could be 'enforced' verbally by making classes 
only able to define operators if they implement an interface 
java.lang.Field (or java.lang.Ring or whatever). The contract 
would go in the documentation for this interfact.

Solution 2. In a future version, perhaps the language could 
directly enforce the contracts in solution 1, using something like 
Design by Contract.

Solution 3: as mentioned above, names are less open to abuse 
than symbols. If names like 'times' have to be used where the 
method is defined, and symbols like '*' can only be used where 
the method is called, abuse is less likely.

Solution 4: by limiting the operators that can be overloaded to 
basic arithmetic, the extreme confusion of overloading (say) '=' 
and '.' can be avoided.


COMBINED SOLUTION
A small number of interfaces should be added to the java.lang 
package, which define combinations of generic methods like 'T 
add(T)', 'T divide(T)', 'T multiply(T)', 'T subtract(T)', 'T 
equalsEquals(t)'. Additional methods like 'T multiply(double)' may 
also be needed. The contracts of these interfaces should specify 
the relationship between add/subtract, add/multiply etc., although 
contracts aren't yet enforceable in the language. Clearly the 
contracts should be such that normal matrices, complex 
numbers etc. should be able to obey them. Any class that 
implements one of these interfaces declares its methods in the 
normal way, e.g. subtract(), which discourages giving them 
bizarre meanings. But when calling one of these methods you 
can use a symbol like '-' as an abbreviation for 'subtract()' if you 
like. Only a very limited set of operators is available for 
overloading in this way: ones that should be allowed probably 
include '+', '-', '*', '/', '==', '<', '<=', '>', '>=' (as well as '+=' etc.); 
ones that should be disallowed probably 
include '.', '=', '<<', '>>', '>>>', '&&' and '||'.


Submitted On 21-FEB-2004
lucretius
A quite different suggestion (already in 4230600) is to allow 
arbitrary Unicode characters in method names, so that 
mathematical symbols could be used. This isn't enough on its 
own because of course you still want to write operator-like 
syntax e.g. 'a x b' instead of 'a.x(b)' .

But here's a slightly different suggestion: that the existing + - * / 
etc. operators are not overloadable, but that you can define new 
operators using a limited set of Unicode characters such as 
2A01: circled plus
2A02: circled multiply
2A38: circled division
2A00: circled dot

The benefits are:
* These are not confusible with the existing arithmetic operators
* They are clearly analogous to these operators
* In maths notation it's legitimate to use these meaning 'plus-like 
operator' and so on. So it would be just about OK to use them for 
operations matrices and complex numbers

The obvious demerit is:
* These are difficult to type in most IDE's.

Overall I prefer my other suggestion (see previous entry) but this 
one could be workable.


Submitted On 11-MAR-2004
fux11
In my opinion,it is not the rigth way of desingning a
programming language to deny all features that could be
abused. if you would like to be on the safe side your have
to remove all operators and use methods instead. so you wont
have the problems with operator-precedence too.

There are some approaches to limit the use of operator
overloading to some types or packages. In my opinion we all
agree that this feature would be very important for
biginteger for example and to access the element of a vector
via [pos] seems to me very comfortable too. 

We should stop this flame-war discussion an think about a
solution to introduce operator overloading in a safe way so
that it can help us all. this is the main reason why i
posted this RFE.



Submitted On 15-MAR-2004
sam_hoff
Operator overloading is definitely easier to read, if it is used in 
the right way. Really, you can't ban useful features, just because 
someone might misuse them.  
 
Say, wouldn't it be unreadable, if you had to say "Hello".concat(" 
World") in stead of "Hello" + " World"? 
 


Submitted On 18-MAR-2004
jschell
Languages can ban useful features just because they 
can be abused...that is why java doesn't have pointers 
like C/C++.


Submitted On 25-MAR-2004
andylarder
And if anyone can come up with a more general 
solution that includes being able to create operators 
with the names cross, dot, perp...


Submitted On 25-MAR-2004
andylarder
Err - Java does not omit pointers because of abuse, 
but because it has no need for them with automatic 
memory management, which is there to make life 
better for developers. Rather like operator overloading. 
In 12 years of c++ development I've never seen 
operator overloading abused, despite having seen 
some of the most awful C++ and Java programs ever. I 
presume none of the objectors could explain what a 
Quaternion, Affine Transformation and Homogeneous 
coordinate are then?


Submitted On 07-APR-2004
jschell
The white paper for Java specifically points out the 
problems that pointers introduced into C++.  It then 
suggests that java will not have those problems 
because of features that it has - this suggests that 
excluding pointers from java due to problems with 
them was a goal and not a side effect.


Submitted On 10-APR-2004
sciwhiz007
I personally agree with the school of thought that states
that just because something CAN be misused doesn't mean it
should be banned from a language. Operator overloading
definitely has its uses, and most people here seem to agree.
When working with complex numbers or BigInteger/BigDecimal,
operator overloading comes in handy. My suggestion (which I
think has been suggested before in the forums) is to limit
overloading to subclasses of Number, and to block
overloading of certain operators, such as = and new.
Excessive use of overloading is dangerous and impossible to
maintain, no doubt, but a risk does not justify the
prevention of its inclusion in the language. To simplify its
implementation, why not make it a feature of the compiler?


Submitted On 10-APR-2004
kevquinn
How about, instead of overloading builtin operators,
creating a syntax for "infix" use of user-defined methods? 
So that perhaps we could write something along the lines of:

complexR = complexA .add (complexB .multiply complexC);

as a syntactic equivalent to the visually problematic:

complexR = complexA.add(complexB.muptiply(complexC));

The idea being that the initial '.' indicates infix method
call syntax.  The class containing the method must be that
of the left hand operator class (perhaps inherited).  The
method must take exactly two parameters, and return the same
type as the first parameter.  The two parameters are
supplied to the method in left-to-right order (as you would
expect).  The change to the language is intended to be
strictly a change syntax not semantics (so yes, it could be
done with a pre-processor but IMO pre-processors are a bad
idea).  Since it's a method invocation, no precedence is
implied or could reasonably be expected by the code writer,
hence the brackets to bind operators not in left-to-right order.

Gets rid of the ugly current  syntax, which suffers from
cascades of brackets in longer examples, and repetitive
occurrences of the class type name.


Submitted On 11-APR-2004
Andrey_Logvinov
I am against operator overloading in Java. Java is 
definitely not a language for heavy scientific 
computations with lots of complicated formulae.  
Operator overloading does make it harder to 
understand the code. Method names (when assigned 
properly) explain what they do, while operator symbols 
just give an unclear hint about nature of the operation 
(e.g. "+" means addition, or maybe concatenation, or 
maybe anything else). It is imossible to say what 
operator does without reading its description or 
examining its implementation.
Surely, there are cases where operators are more 
convenient than methods, but these cases are very 
rare and in real life many programmers will misuse 
this feature.


Submitted On 23-APR-2004
bparun
if u dont know how to use it properly....DONT USE IT, 
just stick to your fancy method names. but, I suggest to 
add operator overloading in java. before u vote against 
it, u should also know that, in C++, THERE ARE 
RULES, for operator overloading. so, just make some 
in java also AND FOLLOW IT. 


Submitted On 25-APR-2004
t.zielinski
Please add operator overloading. Also add rules, so people
can use it  with pleasure and sense.


Submitted On 01-MAY-2004
dprotas
I am rather new to the Java world, but I have a question...
how come everyone loves to have the "+" opereator overloaded
for strings and don't want the power to use it in your own
classes?

I think the excuse of operator overloading being possible
missused is not good enough. Almost every feature of a
language can be abused. Not to mention that the notion of
method names clarifying code comes from actually use good
names, so as I see it, not for having a lot of monkeys you
should stop making razors.


Submitted On 06-MAY-2004
ArneWeise
In my opinion, operator overloading is one of the best 
features of c++. It allows you to create more compact 
code, and the priority between operators if easy to 
understand at a quick glance. Take these examples:

1)   a + b * c  contra  (a + b)  * c
2)   a.plus(b.times(c))  contra  (a.plus(b)).times(c);

For me, the priority system is MUCH easier to interpret.

Secondly (as said above), if you want to obfuscate your 
code, you can do loads of other stuff, who says that 
operator overloading is more confusing than overriding 
functions??

Mathematics just gets ugly and undreadable whith the 
current system. Streaming using i.e the "<<"-operator 
is sweet and compact.

I truly understand the choice of references instead of 
pointers, and also why templates and namespaces 
and other s***t was removed. It all got to cluttery. But 
this feature i miss!

Bottom line: I suggest a change for the better!


Submitted On 14-MAY-2004
nafralet
Operator overloading is already used in java (Strings) 
and with Tiger we will be able to do something that will 
look like it:

Double Result = IntegerA + LongB * doubleC (boxing / 
unboxing)

I don't see why it should not be possible to redefine 
these operators and use them with my own objects. It 
was one of the coolest features when I switched from 
Pascal to C++.

I disagree with people who argue that this feature 
should not find its way into the java language because 
it might be confusing or misused... many people are 
quite confused by polymorphism, many other misuse 
classes the way c developpers used structs... should 
we go back to procedural languages??? I guess not. 
you don't need operator overloading to write 
unreadable code, but this feature would be a great tool 
for many of us.


Submitted On 22-MAY-2004
sjasja
My experience in C++ is that operator overloading is generally used for "kewl tricks" rather than mathematical equations.  "/" for file name concatenation, "+" for anything from hash table insert to display a window within a frame. C++ code maintenance is painful enough, and operator overloading sure doesn't help.

The trouble is, operator overloading not only _CAN_ be abused. Existing practice amply evidences that it _IS_ abused. Again and again, and far more often abused than used.

"If you don't like operator overloading, don't use it" is a non sequitur. Works if you only ever come to contact with your own code and never maintain other's code or use external libraries.

I've maintained complex number matrix math software (electricity  distribution network analysis). I found no problem reading code with add() functions. There are only +-/* anyway, and the number of mathematical operators is vastly larger (sqrt, sum/sigma, matrix construction, set operations, ...)  Having four operators wouldn't have made "math code" look anything like math textbooks anyway. Is a call to Math.sqrt() really that difficult to understand?

In my experience, the pain that comes from all those operator-overloading-obscured libraries in C++ far outweighs any benefit that comes from the ability to do kindergarten math with +-/*.


Submitted On 17-JUN-2004
Kullgen
Adamantly in favor.

I have always felt that the absence of operator overloading in java was a massive oversight and was a violent contradiction to the way the rest of  the language was implemented. 

Objects like String can be concatenated by using the plus sign. It is both logical and intuitive to do so. To prohibit other classes from functioning the same way is simply hypocritical. 

The only argument I see against operator overloading is for “simplicity”. Java developers are already familiar with using operators to perform tasks between two objects. It would actually make the use of complex custom math objects much easier. 


Submitted On 19-JUN-2004
Longlongago
Support.


Submitted On 21-JUN-2004
kself99
Having used C++ then Java for many years, there are many times I could have used operator overloading to simplify the code and make it more, not less understandable. It has been my experiences that the simpler the code is to follow, the easier it is to maintain. The above objections to operator overloading do not hold up to even passing scrutiny. Operator oerloading is one more tool in the language bag for Java that those who can make use of it correctly should  be able to use it. Those who do not understand it or dislike it, should avoid using it until they feel comfortable enough to use it.


Submitted On 26-JUN-2004
aramendig
I support it.


Submitted On 26-JUN-2004
aramendig
I support it.


Submitted On 29-JUN-2004
MaxEronin
support


Submitted On 24-JUL-2004
bob.goldberg
I vote for a limited form of operator overloading that applies to class 
implementations of specific interfaces defined by Java.  In particular, 
consider classes that implement numeric types. 

If you've ever tried to compute the 
sums of the squares of some BigDecimal numbers, or even just compute 
the sum of a List<BigDecimal> iteratively, the syntax required looks 
completely different than for the built-in numeric types and is not very readable or easy to explain.  There is no conceptual reason for making 
BigDecimal so absurdly difficult to manipulate, and IMHO there is no harm in allowing the numeric infix/prefix/postfix operators to function on any 
class that implements a numeric interface that Java can define.   This is not all that different from being able to sort arrays of objects that 
implement the interface Comparable, for example.

Other modest operator overloading cases might be identified.  For example, any class that provides access to ordered elements using an 
integer index might be allowed to use the array subscript notation:  
foo[<int>].  Java can define an interface for this as well, and then 
java.util.List can implement it so you can access or update List elements 
using brackets:  myList[0], myList[1], etc.  

Regarding operator overloading, IMHO it is the abuses of programmers 
who lack the wisdom of good language designers that has given it a bad 
name.  That being the case, good language designers can readily see 
that the two extensions I have suggested make sense and they follow the 
existing semantics of the operators being overloaded.

From a language/compiler standpoint, both of these extensions should be
relatively straight forward and I don't believe they introduce nasty
ambiguities into the language.  Rather, they provide intuitive meaning to
otherwise illegal statements that look like they ought to be legal.



Submitted On 02-AUG-2004
silk.m
No !


Submitted On 02-AUG-2004
dcminter
"Those who do not understand it or dislike it, should avoid using it until they feel comfortable enough to use it."

The worst part of operator overloading is that the designers of libraries which could otherwise be good feel obliged to use it, even when it's not appropriate. Before long you see code of the following variety:

postOffice += message;

Which looks cute to the designer, but causes immense confusion because the semantics of the operator have been abused.

Since this stuff ends up in libraries, we don't have the option to "avoid using it until they feel comfortable enough to use it" since it's others inflicting it upon us.

Please fix other more pressing RFEs before contemplating such fixes.


Submitted On 02-AUG-2004
UlrikaJ
I'm in favour if Java can find it's own flavour of operator overloading just as it has with multiple inheritance. It's important that Java remains a very safe language because that's one important success factor. 

I think operator overloading should be part of a strategy to make Java handle small objects more efficiently, like for example a Complex, a Point3D or a Money class. This is where operator overloading comes in naturally. Maybe a new kind of class (like we already have interface and enum) or keyword will be necessary to restrict its usage to where it belongs.


Submitted On 02-AUG-2004
jschell
"Those who do not understand it or dislike it,..."

I understood, appreciated and used pointers quite effectively in C++.  Not to mention implementing my own memory heaps and new operators.

So we should add all that back into java as well.

I shouldn't be disadvantaged just because thousands of other developers didn't know how to use pointers correctly all of the time.  Certainly if they can figure to stay away from operator overloading they shouldn't have any problem staying away from pointers.



Submitted On 05-AUG-2004
Crixus
I'm all for the ability to overload operators. Personally I find the wrapper classes pretty annoying to use, so at least overload the operators for those classes.

Personally, I believe that overloaded operators makes code easier to read since there is less text and parenthesis, and if a programmer decides to make the relationship between a plus sign and what it actually does confusing, that's his fault. I mean, a few bad programmers shouldn't ruin it for everyone.


Submitted On 17-AUG-2004
bubblelai123
numeric computing always operator computing


Submitted On 09-SEP-2004
nicesai
I strongly favour operator overloading.


Submitted On 14-SEP-2004
insac
I vote for operator overloading for Number subclass.
If this request is accepted, it will be necessary to avoid abuse and backward compatibility (you shouldn't be able to "override" the operator).

Example: we could have new final methods in the J2SE Number subclasses:
operatorAdd, operatorSubtract, operatorMultiply, operatorDivide. They could be simply implemented as 
add, subtract, multiply, divide and they could not be overloaded. The compiler would then substitute the operators with this methods taking care for precedence.

Maybe Java isn't for "advanced maths", but I'd like to point out that sometimes you have to make calculations also for economical software...


Submitted On 20-SEP-2004
kaffiene
I've a long time Java user, but come from a C/C++ hacking background.

When I was learning C++ I thought operator overloading would be great - I use 3d vectors all the time and I thought it would be neat to overload the vector operators.  The problem is that you can't do it.

I can overload + and - well enough, but I can't overload '.' for the dot product and while I can overload * for scale and cross product operations, they inheiret the arithmetic precedence that multiplication has over addition - and for vectors that prescendece does not make sense (why should a cross product have greater prescedence than vector addition?)

That's my major objection to overloading - you can't actually do it properly - not all the mathematical symbols you want are available and the prescedences are all inheireted from a different (perhaps inappropriate) domain.

In addition, if I see a = b + c in Java, I know that i'm looking at arithmatic, if I'm reading c++, I need to know whether any of these are classes and if so, read the code to know wether any of them overload operators,  Having to read class definitions to understand ordinary code is stupid and hurts maintainability.  Reading code like a.equals(b.plus(c)) it is obvious that equals and plus are methods that are attached to classes in a way that a=b+c does not make clear.

So there are two major issues - (1) you can't actually map the domain of the mathematical entities you're modelling correctly anyway (lack of operators and inapproriate inheireted prescedence) and (2) it hurts readability because you can't tell the difference between a line of pure arithmatic and a line of code for which you need to read class definitions to understand.  And I *have* read *heaps* of C++ code that has been difficult to maintain on this score.

I do have a suggestion about how operator overloading might work.  There are three problems to solve - (p1) disambiguating normal operators from method calls, and (p2) the lack of operators along with the (p3) inheireted scope of normal arithmetic operators..

An idea would be to use operators but with a syntactical difference like so:

a := b :+ c;

Where the colon disambiguates between normal and overloaded operartors (this solves (p1) - these are visually different from primitive operators and (p3) - these can have their own scope seperate from the primitive operators)

The other problem (p2) is the lack of operators.  We could solve that by  allowing any method to be used as an infix (and perhaps also prefix and postfx operator)

The method declaration would be something like:

public Operator infix Vector3D  dot (Vector3D a, Vector3D b);

and usage would be like so:

Vector3D a := b :dot c;

(where  the equals operator had already been overloaded using something like the C# syntax)

In the example above, I have used the "infix" keyword.  My idea would be to have infix / postfix and prefix keywords as options and have "infix" as the default if none of these were used.

Anyway... I'm not hanging out for operator overloading, but I've suggest one way in which you could implement it without C++'s drawbacks.


Submitted On 21-SEP-2004
didickman
There's no reason why Java should not be used for numerical computing. In my opinion the features that make Java so simple to use make it quite appealing for numerical computing because you can write code that does what you need far quicker than you could with C++ and performance is rather comparable. Today, for example, my company has a very extensive financial application that is written almost completely in Java despite us needing maximum performance. But when it comes do doing matrix math, complex math, fast fourier transforms, or numerical integration we use established C++ libraries and JNI. Originally this was done for performance reasons, but with the latest JVMs we find that performance is quite good and we'd love to port our code to pure java, but ironically the C++ code is just *much* more readable for someone trying to understand the underlying math. I strongly believe that operator overloading should therefore be added because there should not be a case where C++ is simpler to read than Java. What's more, I think Java risks losing a big chunk of the numerical community (ourselves included) to C# since that language already includes operator overloading.


Submitted On 14-OCT-2004
eder.augusto.penharbel
I strongly favour a complete operator overloading.


Submitted On 30-OCT-2004
ornelyz
I'm waiting for operator overload since I leave c++.
I think that the posible misuse is not a valid argument, because,  if misuse of a feature is a reason to drop it, then drop proxy s, generics, interfaces,  polimorphics, and why not, all of oop, because BAD PROGRAMMERS will misuses them.
if you have bad programmers, maintain their code  was, is and always be a headache, regardless of the language or the specification.  I know this because I did a lot  of code maintaince in c++,  pascal, delphi,  cobol and java,  and believe me,  with or without operator overload bad code will allways exists.
So, don't  let bad programmers rule the language specification.  You just have to think  the way to help to GOOD PROGRAMMERS.


Submitted On 30-OCT-2004
ornelyz
Besides, if you do operator overload with strings,  why I can't do it for my clasess?
it is like eating in front of a hungried AND DO NOT SHARE
that's  evil


Submitted On 03-NOV-2004
frans_lundberg
I want limited operator overloading, only for 
+ - / * = , and only for number-like entities like complex numbers and matrices.
It is absolutely needed to do serious numerical computations 
in Java which many people do or would like to do.
My company has been forced to modify Java to be able to manipulate matrices easier.
We may have to switch to C# in the long run if operator overloading is not added to Java.

An alternative is to use preprocessors, for example a Java file could start with:

preprocessor com.linova.OperatorOverloading;

which means that the class OperatorOverloading will
be used to preprocess the source. This approach is of course more general and can be used for a number of 
new features. Aspect oriented programming for example.

 / Frans Lundberg, www.linova.com


Submitted On 16-NOV-2004
vasaninj1981
No There should not be operator overloading becoz the style of programming becomes more cumbersome


Submitted On 24-NOV-2004
MakerOfJava
We need it!


Submitted On 26-NOV-2004
jianhuasun
vote for it.
we need this very important laguage feature. confusing is not a good reason to exclude the feature. it's probably a good advice  not to abuse it but it's bad not to have it. 


Submitted On 02-FEB-2005
Zeigon
I think it


Submitted On 02-FEB-2005
Zeigon
I think it's a useful feature. I got used to it in C++ and I didn't missused it, as far as I know. It's true that you can replace it with methods like yourClass.plus(yourClass) etc. but it just can take to additional code writting, I mean, if you overload an operator it's easier to understand the code  because of  its syntax and because it's simplier to write, than writting methods for that use.


Submitted On 06-FEB-2005
Nick_Ericson
Please add operator overloading


Submitted On 06-MAR-2005
AlexLamSL
against...


Submitted On 19-MAR-2005
sim085
So, I read some of the points and saw that some here don't agree with it, coz it can be mis-used, and because of code readability.  

Abuse is possible in programming even when developing a simple application.   Take for example programming a simple calculator application.  The ideal way is to do it by following the MVC model, but this does not mean that java does not let you to place all the code in just one class.

Now for me I think that a programmer should be left free to program, while keeping a set of rules that are understandable by everyone.  

What is the difference between making a method plus(...) to add a number an overloading the + operator.  I don't see a differce between comparing two strings by using the .equals(...) method and the == operator.

I would really like to see operator overloading in future versions of java! I think that being there and not use it is much better then not being there at all.  You never know when in you application you will happen to need something like that!


Submitted On 25-MAR-2005
Coffee_Guru
against that overloading crap


Submitted On 08-APR-2005
georg_v
My vote is pro! 

The kernel structures of Language are already implemented mostly without operator overloading. Then the question is "To use or not to use" language features like that in distinct software designs. Project Manager should know answer for this questions. It's a question of distinct design rules and depends on many factors such as devlopers' experience, project's parameters etc.

There is no reason to caponize the programming language removing native OO features. And I ignore all references on the philosophy if philosophy is "Java is a Language for Dummies".

Please include operator overloading and also ability to change method parameters (possible as it was done in c#) in future redactions of language's standard.


Submitted On 13-MAY-2005
Rich_Sedman
Against full operator overloading but the 'infix' ideas mentioned above sound like a good compromise.


Submitted On 03-JUN-2005
kenj0418
Against.

I think this would be useful for a very small set of situations where you are dealing with mathematical-type classes (matricies, complex numbers, etc.).

For any other situation, it isn't necessary, and would tend to make code more difficult to understand.  Besides, I'm sure there are many, more useful features the developers could be working on instead.


Submitted On 07-JUN-2005
hwc
This doesn't get my vote anyway but it should definitely be limited to immutable objects.  We therefore need a way to tag such classes: @immutable?


Submitted On 03-JUL-2005
Ch._Alexopoulos
The world that dominate this topic is "misuse", but nobody explain how can you misuse operator overload in a worst way than you can misuse other futures of language. The only kind of misuse that i found is :
typedef float Coord; 
 class Point  {
 public:
   Point(Coord x=0.0, Coord y=0.0);
   
   friend Point& operator+(const Point&, const Point&);
   friend Point& operator-(const Point&, const Point&);    
   friend Point& operator*(const Point&, const Point&);
   friend Point& operator/(const Point&, const Point&);
    .
    .
  }; 
If you want to make calculation betwen Point's in java nothing prevents you
public class Point
{
Point add(Point p1, Point p2)
{
.
}
Point sub(Point p1, Point p2)
{
.
}
etc
So what is the diferense ?
An uncapable programer can misuse every single future of java. i did a lot of misuseng on java futures in the learning prosses and maybe now i misusing things without knowing about. Language safety is not about to prevent programer from programing but is about of keeping control of things that programer can't control or is very hard to control right, like memory allocation. 
I post this in hope that a future java version implements operator overloading in order to improve language safety.


Submitted On 14-JUL-2005
tschodt
String + operator.

The String + syntax for string concatenation is commonly misunderstood.
Java has primitives and their wrapper classes - you can specify primitive literals in your code.
Java also has a few special classes; Class, String - for which you can specify literals. 
For String it would have been most inconvenient not to be able to specify literals... and it would also have been inconventient not to be able to break up long String literals on multiple lines.
There was a need for a String concatenation operator [you want the compiler to do this concatenation when it can, so adding "public String append(String s)" to the String class would not have done the trick].
Some argue that "+" was not the best choice, it is as good as any.
Because people are quick to adopt something as handy as the String + syntax
it would have been most unintuitive to have it only work with String literals, 
so it was made to work also with String references
[and primitives and objects as well in the form of String.valueOf()].

The String + operator has nothing to do with operator overloading,
the compiler intrinsically understands about the String + operator,
there is nothing in the String class to cater for it [apart from String.valueof()].



[What is wrong with] operator overloading.
A classic example.
operator<<() ; as far back as I recall "<<" has meant left-shift.
IMO the fact that every simple C++ HelloWorld.cpp I have seen uses "<<" to mean "print/stream" means C++ operator overloading is fundamentally flawed.
If part of your work is fixing bugs in other peoples code, this kind of shortcuts are very annoying - you suspect or know a bug is related to left-shift and you don't really want to spend days to spend reading through all the source - so you grep for left-shift - you will get all the streaming statements as well.

Only those who are never asked to fix bugs in other peoples code have the option of practicing "if you don't like it - don't use it".
Yes, bad programmers will make hard-to-maintain code regardless, but code using operator overloading can easily be orders of magnitude more difficult to maintain.

If you want to use operator overloading, use C++.
According to some, there are many other compelling reasons for preferring C++ over Java
<http://nuwen.net/gcc.html> 
Note; I disagree with most of this, IMO several of the assumtions of the author are fundamentally flawed,
however, I have no interest in getting into a vi/emacs type debate).



[Numeric] operator overloading.
Trying to implement operator overloading so it works 
for classes in java.* or java.math.* only seems like an ugly hack.

Rather than enhancing javac to understand operator overloading
how about using a preprocessor to convert your own bastardised form of java to java?
This would not have to involve Sun.
If you make your implementation publicly available and your design is good, your solution will soon be adopted by others.
Here is an example of what I mean.
http://forum.java.sun.com/thread.jspa?threadID=644372


Submitted On 15-JUL-2005
JessHolle
Can I please vote *AGAINST* this?

Anyone asking for this has never had to work with code written by anyone else than themselves and possibly their closest friend.

Operator overloading is cute, giving that symbolic feel, but when used by a development team rather than an individual it quickly becomes very difficult to understand what's going on by reading the code.  Innocuous looking lines of code suddenly have massive side-effects.

Even on solo projects, I'd still avoid operator overloading as I don't have perfect memory of all of my code over the years and operator overloading just makes it harder for me to follow my own code!

C++ *needs* operator overloading to make its form of generics get anywhere.  That's the only valid reason I see for  it in C++ -- and Java's generics don't have this issue.  One of the typical use cases given for using operator overloading in C++ is numerics, but anything but +=, -=, etc, involves wasteful amounts of stack copies by nature -- as you're returning by value otherwise.  This has horrible effects when the value is a large multi-dimensional array.  Thus beyond readability even in C++ I'd urge caution in that the performance side-effects of using operator overloading can be astoundingly bad.

In short, operator overloading in Java would be a useless and confusing mess that serves only as eye-candy for those who don't have enough programming experience to know better.


Submitted On 25-JUL-2005
gbishop
I want to vote against this.


Submitted On 25-JUL-2005
gbishop
There are 21 anti votes.  Lucretius had in interesting idea.  Personally I think a language implementation NOT operator overloading that allows us to easily do marix math is called for.  It should not be overloaded arbitrarily however, much as + for string concatination works, the dot product, dubtraction, addition and multiplication could be created to work on primative arrays, etc.

My primary objection is to letting people overload aribtray classes.  If an array has a dot product that does an expected thing that is defined in the JLS, I'm all for that.

I'm not for GodKnowWhatFooThing = MyFooThing * YourFooThing.


Submitted On 29-JUL-2005
kenj0418
RFE againstVotes;
...
againstVotes += 1;


Submitted On 01-AUG-2005
MrThickie
NO operator overloading please.  The lack of this in Java makes it far better than C++. Operator overloading is one of nastier features of C++.  Even if you believe you can understand your own code it makes sharing and understanding other people's code far more difficult.  No, no, no...


Submitted On 06-AUG-2005
wwk_killer
My vote against.

Super-heroes dreaming of solving all the problems with Mighty Overloading kewl Feature should better start learning javac internals. Just like clever guy Gilad Braha shipped Java generics long before official date, anyone can change javac and publish it. 

You think Javac with overloading will be popular like hot meat loafs? Trust me, 11 visits a day from .edu domain will be a record. 

* * *

Speaking matterly. Let's imagine we have invented our own com.oveloaded.PuperList<Object> with

operator += that adds Object to "this";
operator + that adds all elements of PuperList to "this";

one smarty will write
  fullList = fullList + segments;
and later elements of fullList will be (String) cast; 
of course segments will always empty;

second smarty maintainer will "optimize" with
  fullList += segments;  // it's the same, right???
(not right: last element will be PuperList, not String)

after thoroughful testing, this will be shipped;

BANG -- another Ariadna failure, kiss goodbye to 10 billions $$$. "Damn clever tricks, damn Java, it's so dangerous language!"

Satanic temptation to include overloading? Go work to industry!


Submitted On 06-AUG-2005
JessHolle
If we could just get 4 dummies to wise up and remove their votes this enhancment could drop out of the top 25 and back into the obscurity it deserves.

For that matter Sun should simply say "will not fix" and kill this.  They did this to the limited multiple inheritance proposal of letting interfaces have default method implementations (but still no fields), so why not kill this the same way -- this proposal deserves it.


Submitted On 10-AUG-2005
orinius
Against.

While not "error prone", just as multiple inheritance isn't "confusing", it makes others' code less readable. You can almost always add new features, but never remove.


Submitted On 26-AUG-2005
Fuerte3
Want it. Do not use it in JDK if you hate it, but let people choose and use it if they want.


Submitted On 26-AUG-2005
JessHolle
Fuerte3, the problem is that one cannot simply not use it if you don't like it.  In a larger organization, once such a feature becomes part of the language suddenly you have to spend money preventing engineers from misusing it or spend money dealing with the unmaintainable code that results.

Either way in the real world stupid features like operator overloading cost any development organization consisting of more than a dozen programmers loads of money.


Submitted On 01-SEP-2005
Fuerte3
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconoperatoroverloadingusageguidelines.asp

The following rules outline the guidelines for operator overloading:

    * Define operators on value types that are logical built-in language types, such as the System.Decimal Structure.
    * Provide operator-overloading methods only in the class in which the methods are defined. The C# compiler enforces this guideline.
    * Use the names and signature conventions described in the Common Language Specification (CLS). The C# compiler does this for you automatically.
    * Use operator overloading in cases where it is immediately obvious what the result of the operation will be. For example, it makes sense to be able to subtract one Time value from another Time value and get a TimeSpan. However, it is not appropriate to use the or operator to create the union of two database queries, or to use shift to write to a stream.
    * Overload operators in a symmetric manner. For example, if you overload the equality operator (==), you should also overload the not equal operator(!=).
    * Provide alternate signatures. Most languages do not support operator overloading. For this reason, it is a CLS requirement for all types that overload operators to include a secondary method with an appropriate domain-specific name that provides the equivalent functionality. It is a Common Language Specification (CLS) requirement to provide this secondary method. The following example is CLS-compliant.

[C#]
public struct DateTime 
{
   public static TimeSpan operator -(DateTime t1, DateTime t2) { }
   public static TimeSpan Subtract(DateTime t1, DateTime t2) { }
}



Submitted On 03-SEP-2005
JessHolle
Developers ignore guidelines.  Also, why are you so anxious to emulate C#.  Operator overloading is a prime example of what's C# got *wrong* when it tried to copy Java and throw in much of the C++ kitchen sink.

Operator overloading seems fabulous in single hacker projects.  Once you have to understand other developer's code who did not perfectly follow the guidelines, then you're in for a nightmare.

If someone was foolish enough to add operator overloading too Java they should at least mitigate this effect by providing a standard compiler flag *required* to be available on *all* Java compilers to disallow this feature.


Submitted On 10-SEP-2005
I support adding this feature.

I used C++ before switching to Java, and one of the features I miss most is
operator overloading.  The problems listed, however, are valid, so I propose
an in-between solution, similar to what some others have proposed: 

Allow subclasses of Number to overload the arithmetic operators (+, -, *, /, %,
and unary -) the assignment operators (+=, -=, *=, /=, %=, ++, --), and the
relational operators (<, >, <=, >=), or some subset of these.
Allow classes implementing Collection (or extending some other superclass,
such as AbstractCollection or an as-yet-to-be-added one) to overload [int].
Continue allowing String to overload +.
This would provide benefit in situations where it is clear, and prevents misuse
(such as:
&tab;name1=name2%name3;
&tab;//name1 is now the first name of name2 and the last name of name3
).


Submitted On 11-SEP-2005
hlovatt
I think operator overloading is difficult to do and current approaches from other languages are lacking, that is why so many people are against it. We need a fresh approach because operators are slightly different than normal methods in that they are related to each other and in general efficiency is a concern. Let me address efficiency first, you don't want:


r = a + b + c + d


to be:


r = a.add(b).add(c).add(d)


because each plus needs to make a new object (think Strings here). You want:


r = a + b + c + d


to be something like:


final SomeType temp = a.toOperableForm();
temp.setAdd(b);
temp.setAdd(c);
temp.setAdd(d);
r = temp.fromOperableForm();


This is how String behaves, with good reason! Therefore I suggest defining:


public interface AddOperator< T extends Addable< T > > {
    T toOperableForm(); /* makes a deep copy and can cast if required */
}
public interface Addable< T extends AddOperator< T > > {
    T fromOperableForm(); /* makes a deep copy */
    void setAdd( T t ); /* changes the value by adding */
    T unity(); /* returns unity (1) */
}


Then a class that implements AddOperator can be used with operators +, +=, ++ (pre), and ++ (post) by transforming the code as shown above for +. String would therefore implement AddOperator and StringBuilder Addable. Some classes may implement both AddOperator and Addable.

Note how the programmer implements setAdd and unity; but all the operators +, +=, ++ (pre), and ++ (post) are defined in terms of just setAdd and unity, thus giving consistency between operations. This is the second problem with operator overloading addressed, i.e. when temp = a; temp + b != a += b

Similarly the interfaces:


interface ArithmeticOperators< T extends Arithmeticable< T > > extends AddOperator< T > {
    /* empty */
}
interface Arithmeticable< T extends ArithmeticOperators< T > > extends Addable< T > {
    void setDivide( T t );
    void setMultiple( T t );
    void setSubtract( T t );
}


And a class that implemented ArithmeticOperators could be used with operators like AddOperator above but with /, *, and - as well as +, i.e. /=, *=, -=, etc.

Comparing is simpler than arithmetic because an intermediate class isn't needed because compare doesn't change any values:


public interface CompareOperators< T extends Comparable< T > > extends Comparable< T > { /* compatible with old code because it extends Comparable */
    /* empty */
}



Would allow <, >, !=, and == for a class that implemented CompareOperators. Currently, if you are implementing Comparable you shouldn't use == and equals should call compareTo. This solution elevates the problem of calling ==, but the problem of people forgetting equals remains (but is lessened since most people will use ==).


Submitted On 20-SEP-2005
macrules2
Against++

Operator overloading is available in c++, feel free to go there and use it.


Submitted On 30-SEP-2005
Jason-Mehrens
Against.  However, a Java(TM) user should be able to use all the operators that int supports on the java.math.BigInteger and the valid double operators on the java.math.BigDecimal.  The reasoning is that auto(un)boxing has promoted *most* of operators that work on primitives to the wrapper classes.  The compiler should be modified so operators on the java.math.BigDecimal and java.math.BigInteger map to the appropriate function, the same way auto(un)boxing works.  The != and == operators should still compare references though.

//Auto(un)boxing equals operator overloading for wrappers.
public class BoxingOperator {
  public static void main(String[] args) {
    final int primitive = 2;
    Integer X = new Integer(primitive);
    Integer Y = new Integer(2);
    
    System.out.println(X.getClass().getName());
    System.out.println(Y.getClass().getName());
    System.out.println(X == Y);
    System.out.println(X != Y);
    System.out.println(X == primitive);
    System.out.println(X != primitive);
    
    System.out.println(X - Y);
    System.out.println(X + Y);
    System.out.println(X < Y);
    System.out.println(X > Y);
    System.out.println(X <= Y);
    System.out.println(X >= Y);
    System.out.println(-X);
    System.out.println(-Y);
    System.out.println(X * Y);
    System.out.println(X / Y);
    System.out.println(X % Y);
    System.out.println(X++);
    System.out.println(X--);
    System.out.println(--X);
    System.out.println(++X);
    System.out.println(X += Y);
    System.out.println(X -= Y);
    System.out.println(X *= Y);
    System.out.println(X /= Y);
    
    System.out.println(X |= Y);
    System.out.println(X ^= Y);
    System.out.println(X &= Y);
    System.out.println(X %= Y);
    System.out.println(X & Y);
    System.out.println(X | Y);
    System.out.println(X ^ Y);
    System.out.println(X >>> Y); //doesn't apply to BigInteger
    System.out.println(X >> Y);
    System.out.println(X << Y);
  }
}


Submitted On 30-SEP-2005
amengual
It is fun that the RFE poster put an example of a wrong use of operator overloading.

However, Sun should do something to make easier write code with vectors, matrices, and spinors. If you have to deal with lots of large matrix/spinor equations, Java is essentially unusable.

People often dismiss mathematical software as being a 'high school' feature; not only is this false, it prevents lots of people from learning Java in universities.

Lots of people learn programming during undergraduated science studies, using it mostly for mathematics. And their teachers are obviously going to choose .NET instead of Java for this reason.


Submitted On 18-OCT-2005
fux11
I didn't post any examples. The java-team did. I only wrote: "This post is made to give the people the chance to discuss and vote." Don't  blame me ;)


Submitted On 18-OCT-2005
fux11
TOP 25 ;))  i want more


Submitted On 28-OCT-2005
Ixchel
I have mixed feelings about allowing operator overloading of symmetrical binary operators such as +, -, etc. because making them work in a properly typesafe manner can be quite difficult.

However, I would love to see operator overloading for certain unary left-binding and right-binding operators. For instance, the array index operator ("[ ]") seems a natural for accessing collections such as List and Map. In fact, I'd like to see anything that implements List and/or Map automatically be accessible via these. So instead of:

     Map foo;
     foo.put("A", "B")
we could write:
     foo["A"] = "B";


Submitted On 09-NOV-2005
java is just not the language for it. properties, operator overload, etc.... autoboxing isalready _enough_


Submitted On 12-NOV-2005
STREMLER
Against.

(Although it would be neat to have matrix-multiplication on numeric arrays, transparent handling of big numbers, map gets with [ ], etc.  -- but if the price of having those is to have to put up with code by programmers who think that << should map to System.out.println, well, I'd rather do without.)


Submitted On 18-NOV-2005
Mike-Skells
I support this
 The qustion is - if you dont support it then do you believe that the JLS is wrong currently. After all string operations currents support the + operator. 

Why it this a special case and BigDecimal is not

I am opposed to special cases in languages in general.

Any facility can be abused, and if you look hard enough there is abuse in the current JDK classes. This in itself does not mean that facilities should not be used.

Consider the operator overloading that is in C#. It allow some operator to be overloaded, for example adding and removing listeners
x.listener += this
x.listener -= this

Some limitted allowence for overloading should be allowed,Not the full set of C++, but closer to (and maybe more restrictive than) C#


Submitted On 20-NOV-2005
JessHolle
x.listener += this ???

Yuck!

What does this buy anyone other than another way to have to read listener addition?  It's cute, but not really helpful to anyone.


Submitted On 29-NOV-2005
kartheek.datta
For operator overloading. 

One of the primary reasons being we need to have a complete implementation of Generics. The current Generics features does not let you create your own Generic types and also does not work wtih primitive types. We need operator overloading more in the sense of achieving a fully functional Generics, than in terms of radically redifining operators. 


Submitted On 30-NOV-2005
Sergey_Vladimirov
against


Submitted On 02-DEC-2005
drivingmenuts
I vote FOR but only for numeric wrapper subclasses and only the major four operations (add, subtract, multiply, divide).

This is a reasonable solution in that it minimizes whatever damage some of you feel will occur and allows operations on those classes to be coded in a way that makes sense.

If you fear that people will start writing convoluted code, consider this: Does the responsibility for good code lie with the programmer or with the language? Personally, I feel it lies with the programmer. Certainly, a language should encourage best practice, but ultimately, it's the programmer's responsibility.

Fearing that someone will "produce bad code" does not seem like a valid argument, in that it is subjective and not objective. There is no standard for "bad code" - it's only code that you don't like. 


Submitted On 16-FEB-2006
hwc
I'm not that keen on the idea unless it is restricted to immutable types - like primitives, + or - should always create a new object.

Of course, this would be a lot easier if classes could be marked as immutable, e.g.

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4617197


Submitted On 20-FEB-2006
jschell
Addressing two of the arguments presented.

1. "Strings already use overloading".  No they do not.  Basic and perl both have a string concatenation operator and no one claims that they use operator overloading.  Floating points are addable in most languages and yet no one claims that they are using overloading.  C++ strings do use operator overloading though.  That is because operator overloading is a specifically defined feature and the string class (not the language) overloads the plus operator to provide concatentation.

2. "People don't have to use it if they don't like it".  The problem with operator overloading in C++ is not that people can use but rather that people DO use it.  They use it for far more purposes than those which are appropriate.  So the abuse far exceeds the correct usage.  It the factor that it is used and the most of the time it is used incorrectly which makes it a poor addition to a language (any language.)


Submitted On 03-MAR-2006
renkrad
Someone posted here :
"Languages can ban useful features just because they 
can be abused... (...)"
If this is true why there is still programing languages?! Or even better, why does assemble still exist? This is the worse argument i ever hear... The developer should not be limited but oriented, the way, you should do this but there are some special situations where you may need to do that... That's why there is the best practices guide! Basicly, the language was made to serve the developer and not the other way around.


This is a good feature, though not a vital one. This is very usefull in situations like :
  - we have an instance of Integer, Short (and other numerical class) and wish to perfom some actions like add, multiply, divide, etc...;
  - wish to merge two objects like lists, strings(already "suported"), maps, etc;
and many other that i don't recall of right now.

One vote from me.


Submitted On 07-MAR-2006
ArtBlair
How about a compromise? It looks like almost everyone requesting this just wants to do matrix/vector math without resorting to endless nested functions. So instead of allowing users to overload operators how about Sun providing NEW operators just for matrix math. 

They would operate on 1 and 2 dimensional arrays or on new Matrix and MathVector classes (cant use Vector, it's taken.) This alone would make a world of difference to us number crunchers. 

The rules of matrix algebra are as firmly established as those of scalar algebra so there should be no confusion. For those complaining about confusing code, try unraveling dozens of nested methods into the original equation. That's confusion.

The needed operators are: addition, subtraction, multiplication, dotproduct, and crossproduct. A unary negation (a=-b) would be nice too. You could just prefix the scalar operators with a dot. The dot and cross product would need new operators. There are still a few unused symbols (#) on my keyboard. It could even be done with a preprocessor in javac. I THINK this would appease those who are worried about unmaintainable code.

I plead on bended knee for this. I do ALOT of matrix math. My code is hideous and bloated for lack of matrix operators. New operators would keep everyone happy or at least quiet.


Submitted On 09-MAR-2006
Sheepy
I'm against a generic operator overloading mechanism, too.  

So maybe we can have a new RFE for matrix and vector operators?


Submitted On 10-MAR-2006
jschell
The argument is not just "it can be abused".

Instead it is a comparison of how often the feature is useful (used correctly) versus how often it is abused.

Numerics is the only general area with a good argument for overloading.  Numerics is a very small sub-section of the overall programming community.  Thus the suggestion to limit it in java to just numerics meets that particular need without exposing it to abuse in other areas.


Submitted On 13-MAR-2006
martinr2
pro.

It's a shame explaining someone new to Java that for working with BigDecimal, you have to use clumsy methods instead of elegant operators.
Remember that float/double are not suitable for financial computations.

I don't need operators for adding/removing listeners and stuff, but it's definitely bad not having them for computational purposes.

What about allowing overloading only for subclasses of java.lang.Number?


Submitted On 15-MAR-2006
Oh dear. What a shame that C++ has poisoned yet another well.

Operator overloading has been done well in many other languages, notably Algol 68 all the way up to Haskell in ways that are well defined, rigorous and not likely to be abused.

Voting against simply because a feature might be abused is also a very poor philosophy - particularly in this day and age of intelligent IDEs. Should we ban classes called Float or Integer that aren't in java.lang.

Quite simply operator overloading is too damn useful. Doing serious vector/matrix algebra without operators is confusing and error prone - something that Java otherwise avoids being. I'd rather risk a little abuse for a feature that means I can actually read my code.


Submitted On 17-MAR-2006
_Andre_
I t would be very helpful to use operator overloading
for BigDecimal and BigInteger (like java.lang.String)
for implementing financial applications.

Andre


Submitted On 17-MAR-2006
lu.timdale
I think for BigDecimal, there should be an exception.

Also, getters and setters should be simplified using operator overloading ala c#.  It really is beautiful to be able to simply define a member variable as public (for both read and write) and later be able to restric how it is used.  
C#
public int myNumber;
For example, you can make it read-only or write-only.
private int someNumber; // private local variable
public int myNumber {  
    get { return someNumber; }
    set { someNumber = value }
}
Operator overloading is used to overload the = operator and the setter is called.  When the variable is retrieved (simply by calling its name) the getter is called.  This is very handy as your accessor code is very clean.
C#                              vs     Java
myNumber = 3;                setMyNumber(3);     and
x = myNumber + 1            x = getMyNumber() + 1
In Java, you have to due the arduous task of creating getters and setters and make sure to call them even though in 99% of the cases, you will not have custom logic in those get/set methods.  C# lets you add that logic later and use the conventional means to access/set the variable (by name/via =). 


The point is that there is definitely benefit to using operator overloading where it makes sense (in the cases I listed above).  Otherwise, it probably does not really add much value.


Submitted On 20-MAR-2006
yes please!


Submitted On 12-APR-2006
You can produce unreable code with anything, including current java. Any feature can be abused - "you can't make things foolproof because fools are so ingenious".

But if used properly, operator overloading can improve readability a _lot_. 
I could point without hesitating to about 40 classes in my current project alone, and several hundred in my repository that would really benefit from operator overloading. Replacing all those subsequent .add() .append() and .concatenate() calls by a + alone would be a relief.

And there's no proper generics without a notation that allows them to use in a generic way.

I vote for operator overloading.


Submitted On 27-APR-2006
Juan_van_den_Anker
against++ 


Submitted On 02-MAY-2006
aniseed
against++;


Submitted On 03-MAY-2006
Madathil_Prasad
Against. 


Submitted On 06-MAY-2006
jschell
Stating it again - the problem is NOT just that operator overloading can be misused.

The problem is that that the ADVANTAGE of adding it is more than offset by the DISADVANTAGE of the misuse.

Two parts, not one part.


Submitted On 07-MAY-2006
Elijah_Epifanov
Against.
The only possible is overloading private field acces with getters and setters, but there are some problems with ambiguity accessing these fields when they are accessible as fields (i.e. from within same class)


Submitted On 11-MAY-2006
VJLionHeart
Insane Request. Kill It


Submitted On 19-MAY-2006
renkrad
This not important but very usefull to make the code easier to read. Just intruct the developers, give warning when the operator overloading is used like the 'unsafe' related with the generics.

How about defining an interface that states that a certain class suports operator overloading? The same way as Clonable and Serializable.


Submitted On 23-MAY-2006
If it's 'abuse' to make foo += bar do something odd, why isn't it equally abusive to make foo.add( bar ) do something odd?

Certainly, I seems ok to add a compiler feature which replaces:

a + b + c

in the source code with

a.add( b.add( c ) )

in the 'actual' code, and requires a.class to implement, say, an Addable<b.class> interface which has a lone add( B b ) method. Pure syntactic sugar (which is all most people are asking for).

The problem I have with operator overloading in general (aside from overzealous usage, such as the << and >> silliness in C++) is that the assignment operator has a very specific and well-defined behaviour when applied to Objects, which doesn't play well with +=, -= etc. In particular:

a = x
b = a
a += y
c = b
b = b + z

If a, b and c are values, (as in C++ and maths), a == x + y, b == x + z, c = x.
If a, b and c are references, (as in Java), a == x + y, b == x + y + z, c = x + y.

And, last time I checked, C# actually resulted in a == x + y, b == x + z, c = x (because it directly substitues x += y for x = x + y).

Which is 'correct'?


Submitted On 28-MAY-2006
hamlink
I'd like to see overloaded operators. See arguement at http://onthethought.blogspot.com/2004/11/java-and-operator-overloading.html

--larry


Submitted On 29-MAY-2006
Daniel.Winterstein
Strongly *for* - with restrictions.
Overloading + and * would make for much cleaner code when doing mathematics with objects. Which is a good thing, since such code will typically be quite difficult to follow.

CliffNotes's suggestion of having limited operator overloading based around an interface is a good one. I would favour a set of interfaces, one for each over-loadable operator.
E.g. Addable, Multipliable, Dividable, Subtractable.
They can use generics to keep type safety.

I think only these basic arithmetical operators should be overloadable (and I'm not sure about divide). The C++ approach of allowing anything to be overloaded is insane.
 - Dan


Submitted On 22-JUN-2006
DewinCymraeg
That class of developer which thinks playing with features in inappropriate ways is 'fun', without regard to maintainability and transparency could very easily cause havoc to a project's codebase. And most codebases, in my experience, are already in a mess.

I think, in balance, I would rather do without it.


Submitted On 30-JUN-2006
Productivity wise, operator overloading would be a real bonus. I see no reason to curtail how programmers express the solutions to their problems. Yes, there will be programmers that abuse this facility and create 'unreadable' code - but those same programmers probably make these kinds of errors anyway. It's up to the programmers, not the language designers, whether or not they want to use a facility of the language. The ability for code to be 'Self documenting' is far less of a priority than the ability of the programmer to efficiently produce a solution for the problem in hand. Anything that helps him do that should be included.


Submitted On 07-JUL-2006
busitech
The need for normal math operators to work with BigDecimal is very serious. 

Especially with comparisons, as I can barely read my code after I'm through writing it.

Example: 

if (quantityOrdered.compareTo(quantityAvailable) <= 0) {
     quantityAvailable = quantityAvailable.subtract(quantityOrdered);
}

if (quantityOrdered <= quantityAvailable)
     quantityAvailable -= quantityOrdered;


Submitted On 07-JUL-2006
Strongly in favor of operator overloading.


Submitted On 22-JUL-2006
I am in strong support of providing operator notation for classes. The main objection is abuse, but that already applies for existing features. Denying it to developers that will not abuse is rather limiting and "paternatilistic". Other languages like Eiffel support this (and B Meyer is not known for allowing "silly" features),  and there is little reason not to support but a lot of reasons to support this feature (see other comments).

I would like to see a proposal that includes many operators being made available, maybe going as far as using Unicode characters (see Fortress language which includes G Steele as designer!).


Submitted On 25-JUL-2006
cadrian
I'd like to add that Eiffel support for operators is limited to "arithmetic" operators (plus free ones, but that's not the question here).

The main point is, there is NO WAY to overload the == operator (but equals() can be redefined of course), and that's why this feature is USEFUL.

SmartEiffel still rules.


Submitted On 03-AUG-2006
francisdb
Maybe a few math classes like vector3d could have default operator overloading? But this will cause problems for existing code, there should be a clean way to add this feature.
A few new operators with the old ones kept as they are?


Submitted On 20-AUG-2006
As far as I can tell, the proposal of hlovatt on 11-SEP-2005 regarding arithmetic operator overloading is based on an analogy with the string concatenation, which consists in:

- an inmutable type : String
- a mutable type : StringBuffer
- a method that converts the former into the latter : new StringBuffer(String)
- a method that deals with the += operator : StringBuffer.append(String)
- a method that converts back to the inmutable type : StringBuffer.toString()

The + operator is dealt with in terms of the above mechanism : c = a + b is translated into c = a ; c += b .

I would like to suggest that this could be managed the other way around : one could just have an inmutable type (String) with the following method:

String concat(String string)

, which would deal with the + operator as in c = a + b. The a += b syntax would be translated into a = a + b .

This would be my preferred way of dealing with arithmetic operations. The first reason is that, when there is just one value added, it does better performance-wise:

a = a + b ; // only one object creation

c = a.mutable() ; c += b ; a = c.inmutable() ; // two object creations

The second and most important reason is that, in short, there is no assignment operator in mathematics. Overloading arithmetic operators makes sense especially when writing math expression, which are (in principle) free from assignments. The assignment only comes in the end, because what I'm doing is writing a program, but what needs the clarity brought by operator overloading is mostly the math expression. We have for example:

cos(x) = (e^(i*x)+e^(-i*x))/2

In current java, this is written:

MyDouble cosx = exp(i.multiply(x)).add(exp(i.multiply(x).negate())).divide(new MyDouble(2));

With operator overloading, we would have:

MyDouble cosx = (exp(i*x)+exp(-i*x))/new MyDouble(2);

, which is almost as clear as the text mode math expression above.

In practice, here is how it could be done. There would be an Arithmetic interface:

public interface Arithmetic<T extends Arithmetic<T>> {
    T add(T t);
    T subtract(T t);
    T multiply(T t);
    T divide(T t);
    T negate(); // to handle unary "-" (possibly)
}

, which could be implemented by custom classes, the java.math classes, and the java.lang.Number subclasses. In this last case, it would bypass the auto(un)boxing, as in:

Integer a, b, c;
c = a + b; // calls a.add(b), temporary conversion to int not needed

As the developer of one of the rare symbolic (not only numeric) java math program around, I must say that such a feature would be really useful to me.


Submitted On 20-AUG-2006
A third reason to prefer overloading operators on inmutable types is that it is not always convenient/possible not to create a new object for storing the result, for instance in Complex multiplication.


Submitted On 21-AUG-2006
lfschuck
against...

...except maybe if limited to numerical-related classes... Number, vector, matrix and the like!


Submitted On 22-AUG-2006
Possibly add to the Arithmetic interface above the following method:

    T pow(int n);

This would match the "^" operator when applied to the considered type. It could be misleading with the current ^ though (bitwise xor). Maybe ** then ?


Submitted On 23-AUG-2006
hlovatt
Re: above posts

The reason that I suggested intermediate types that are mutable is for efficiency and flexibility. You give the example:

c = a + b

which is translated into:

temp = a.toMutable();
temp.setAdd( b );
c = temp.fromMutable();

Which, as you say potentially creates two objects (but see below), whereas an add method that returned a new object would only create one. However another example:

y = a * x * x + b * x + c;

Shows the reverse situation where using a mutable temporary saves creation of objects. The above is translated into:

temp1 = a.toMutable();
temp1.setMultiply( x );
temp1.setMultiple( x );
temp2 = b.toMutable();
temp2.setMultiply( x );
temp1.setAdd( temp2 );
temp1.setAdd( c );
y = temp.fromMutable();

Which creates 3 objects. The alternative translation:

y = a.multiply( x );
y = temp1.multiply( x );
temp = b.multiply( x );
y = y.add( temp );
y = y.add( c );

Creates 5 objects. So which method is best depends on the expressions in question and the cost of creating the objects. With my proposal you also get a nice bit of flexibility:

1. If the object is mutable only (no immutable companion class) and therefore implements *both* Addable and AddOperator then fromMutable simply returns this. Thus avoiding an object creation.

2. Many high performance matrix packages merge operations, for example x = a x + b is a BLAS function. You can detect these potentially mergable operations by making setAdd etc. simply note their arguments and the fact that they have been called, but otherwise doing nothing. Then when toMutable is called the operations required are merged and executed. This is how the high performance C++ template numerical libraries work.

So on balance I thought the copying to a mutable form was best.


Submitted On 24-AUG-2006
All right (I assume you are hlovatt , I am raphael dot jolly at free dot fr , the author of the posts of 20-AUG-2006 and 22-AUG-2006. I don't know why usernames cease to display).

The problem is related to storing temporary results. One has to use as few registers as possible. I agree that your solution is better in this respect. I also understand that it makes it possible to take advantage of cpu-provided multiply-and-add instructions for instance.

However there remains my objection that it is not always relevant to store intermediary results anywhere but in a new instance of the class. Take for instance the complex multiplication:

c.r = x.r*y.r-x.i*y.i;
c.i = x.r*y.i+x.i*y.r;

You can't store the result directly in (say) x because you need it to keep its integrity all along the calculation. The same applies to matrices etc. In such cases, even if you use an accumulating mutable class, you will need to allocate some space to store temporary results.

Another point is that, as Giese says in http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4087427 on 28-APR-2000, a "buffered" solution may quickly end up with something large and complicated : one will have to define not one but two classes for each set of overloaded operators.

Let's summarize:

- scalar addition or multiplication : buffered solution better
- composite (complex, matrix, ...) addition : buffered solution better
- composite multiplication : "allocated" solution better

By the way there is an issue with your interface definitions:

public interface AddOperator< T extends Addable< U extends AddOperator<T> > >

public interface Addable< T extends AddOperator< U extends Addable<T> > >

(unless the two interfaces are implemented by the same class).

Ok. Here's my view of a buffered solution.

- an empty Arithmetic interface:

public interface Arithmetic<T extends Arithmetic<T>> {}

- an ArithmeticBuffer type. The problem is to get a buffer from the immutable type. In strings, this is handled by the constructor : new StringBuffer(string). However we can't specify it with an interface, so let's take an abstract class:

public abstract class ArithmeticBuffer<T extends Arithmetic<T>> {
    public abstract ArithmeticBuffer(T t);

    public abstract add(T t);
    public abstract subtract(T t);
    public abstract multiply(T t);
    public abstract divide(T t);
    public abstract negate(); // possibly

    public abstract T toArithmetic();
}

Every time we encounter an operator, say +, applied to the considered type, say MyInteger implements Arithmetic, we would search (remains to know how) for the corresponding MyIntegerBuffer extends ArithmeticBuffer, and then:

1 - instantiate it with the first operand as the constructor argument.
2 - call the ArithmeticBuffer.add() method with the second operand as the argument.
3 - call the ArithmeticBuffer.toArithmetic() method to get the result.

The java language would be altered so that java.lang.Number implements Arithmetic and java.math.* both extend ArithmeticBuffer and implement Arithmetic.


Submitted On 27-AUG-2006
Operator Overloading is silly. The simple fact is that java was meant to be an OBJECT ORIENTED LANGUAGE, even if it is not pure OO.  
Be happy with the primitives and operators that are already part of the language.


Submitted On 02-OCT-2006
jplinhares
I'm against operator overloading in Java.


Submitted On 04-OCT-2006
I'm for it. Its a handy feature.


Submitted On 18-OCT-2006
Zza
Letting coders define operator behaviors is a bad idea. They'll do stupid, unconventional, and confusing things like defining m % n as a function that maps m onto the range (-n, n), rather than to the range [0, n).


Submitted On 25-OCT-2006
AllanWax
I'm *against* this.  If you're the person writing the code, overloading '+' to mean add this record to the database but only if it does not exist and is permitted by security is at best cute and completely opaque to the next person who has to read and understand the code.  I don't like cuteness and *do* like code to be understandable to the *next* person reading it, let alone trying to debug it.  Oh yes, I forgot to mention that "+" for this other database also mean call the service desk and arrange a repair call.  Coding should be straight forward and not obfuscated.


Submitted On 26-OCT-2006
TrakTrakTrak
For.

Reasons: 

1. BigInter is a pain to use. 

2. Just because C++ does it wrong doesn't mean it can only be done badly. To me that's a big strawman.

3. Many opponents claim it's abused, yet provide little proof of its abuses.

4. Conversely proponents provide ample examples of its usefulness.

Here's a way to make it not suck: contrary to C++, make it so that an overload is merely an alias to a normal method, so that users of the implementation can switch to standard notation where it's more appropriate, and to conserve backward compatibility. For example:

bigint.add(bigint2) <-> bigint+bigint2



Submitted On 01-NOV-2006
I think the very fact this RFE has been open for over three years says much about the development of the Java language. Java could have been so so so great if it wasn't for all the woolly academic pureists who think they know better and say, "oh, the silly stupid programmers will abuse it!"  This feature should be present for those that want it. If you like it use it. If you don't like it, then don't use it and shut the f*k up. 

You know, It's the same with swing. Java GUI could have been so so great if the damn woolly academic purists at the helm were replaced by real people with some business sense who actually listened to the demands of the users. But no, Swing had to be native with its own shitty look and feel, all in the name of purity.

And then along comes C# - magically addressing all these issues in a superbly elegant way. I think .NET is closer to the "write once, run anywhere" paradigm than many people appreciate and unless you people wake up and stop being so damn pure for the sake of purity then Java will die as a language and as a platform.


Submitted On 05-NOV-2006
flowerp
I'm *for* this. 

As a long time C++ user I'm very much aware of the mayhem random operator overloading can cause. One only has to look at ios::operator! to understand this point. In ios classes, operator ! is used as a replacement for fail(), as in: if ( !inputStream) {...}. However, in C++ !Object is normally read as Object != null. 
In order to be able to read the above statement, one has to know inputStream is of a ios derived type, which redefines operator !. I think this is a bad example of operator overloading.

However, for many other cases most people would have to agree operator overloading is a Good Thing. In Java we already have them for strings and enums and in EL the [] operator is used.

Currently in plain Java [] has practically more or less disappeared from the language since most people favor collection classes instead of native arrays. If collection classes are supposed to be the safe equivalent for these native arrays, why not allow the [] operator for them? Sun has already agreed that it's a good idea for EL. 

Using [] in collections gives me an extra visual cue that I'm 'indexing' or 'addressing' a data structure and not performing an operation. Technically there is, of course, no difference but conceptually there is.

So, why not just allow operator overloading for specific, well-defined cases? Like put & get in Collections and the math operators for Numbers.


Submitted On 06-NOV-2006
For..
in creating new classes and such, it can make your code a lot more readable plus a lot smaller. i hate the sumsum.Add() sort-of methods, however i like the idea of OO. Object Oriented programming doesn't mean you need to be narrow of view & put Everything in methods. I mean there are operators in java, operator overloading has been found out a long time ago :p, you don't Have to use it if you don't like it... i don't see why one would vote against?



how would you all have liked it if we had to write:
System.out.println((new String("date/time: ").add(dateFormatter.format(dNow))).add("; rights: "));
and so on.. i think we all agree that, in this example with Strings, the operator + for concatenation Really makes the lot More readable. i think infinitely more classes have this 'problem' and classes that people think up, might be better and easier to use when operator overloading is possible.
just my 2 cents


Submitted On 17-NOV-2006
invictus2
As java is the very essence of object orientation and abstraction I would really like operator operloading. It doesnt have to be implemented in the java libraries, but should be at least optional for us who use it alot.


Submitted On 27-NOV-2006
My two cents: one cent against, and one cent for.

For me, the question isn't whether Java should have operator overloading?  It is, how can I express my domain in a concise, readable manner using Java?

When I model of problem domain, I often wish to describe a action within that domain using a simple syntax.  For numeric domains, I want to use equations.  For parsing, I want to use a grammar.  For business logic, I want to use rules.  What I want, is a domain specific language (DSL).  Now, I can step out of Java and into a DSL.  However, this normally brings with it a heavy handed approach, and a non-trivial learning curve.  For some applications this is the appropriate direction.  For others, the gap between the expressiveness of the DSL and the need for general programming constructs is too great.  In these cases, I would rather stay within the general purpose language (GPL), except in specific, domain oriented areas.  

Operator overloading allows me to inject my domain objects into the expression language of C++ in many ways.  It provides a way for me to build a pseudo-DSL on top of the GPL.  I can then allow complex numeric actions be represented in an equation-like syntax, and so on.  The resulting code may not be as clean, or as efficient, as would be achievable through a true DSL.  However, I can often reach a good balance.

Java provides a general purpose expression language, and does not allow me to inject my domain objects except in very rigorous ways.  The most obvious is the method call.  The result is that I must express my domain actions using this less-elegant, sometimes cumbersome syntax.

Techniques for defining and using limited DSL's can be brought to Java.  There already exist preprocessors for similar purposes.  I would suggest a more integrated and generic approach.  It should be able to encompass existing constructs, such regualr expressions.  I would also love to see it used to cleanup some of the existing ickier bits in Java.  Mathimatical expressions and string composition being at the top of the list.

Java can allow operator overloading, and I will use the feature in a similar manner to that of C++.  Or, Java can provide another way for me to define and use a limited DSL within the larger context of the language, and I would be more than happy to us it instead.  Or, Java can do nothing to address this need, and I will continue to dream of the possibilities.

Java is a GPL.  Can it also be an environment for building limited DSL's?  Should it be?  I would rather have a formal way to define and use little DSL's, and not have operator overloading.  But if no better option is available, then I will take operator overloading over nothing at all.


Submitted On 27-NOV-2006
My two cents: one cent against, and one cent for.

For me, the question isn't whether Java should have operator overloading?  It is, how can I express my domain in a concise, readable manner using Java?

When I model of problem domain, I often wish to describe a action within that domain using a simple syntax.  For numeric domains, I want to use equations.  For parsing, I want to use a grammar.  For business logic, I want to use rules.  What I want, is a domain specific language (DSL).  Now, I can step out of Java and into a DSL.  However, this normally brings with it a heavy handed approach, and a non-trivial learning curve.  For some applications this is the appropriate direction.  For others, the gap between the expressiveness of the DSL and the need for general programming constructs is too great.  In these cases, I would rather stay within the general purpose language (GPL), except in specific, domain oriented areas.  

Operator overloading allows me to inject my domain objects into the expression language of C++ in many ways.  It provides a way for me to build a pseudo-DSL on top of the GPL.  I can then allow complex numeric actions be represented in an equation-like syntax, and so on.  The resulting code may not be as clean, or as efficient, as would be achievable through a true DSL.  However, I can often reach a good balance.

Java provides a general purpose expression language, and does not allow me to inject my domain objects except in very rigorous ways.  The most obvious is the method call.  The result is that I must express my domain actions using this less-elegant, sometimes cumbersome syntax.

Techniques for defining and using limited DSL's can be brought to Java.  There already exist preprocessors for similar purposes.  I would suggest a more integrated and generic approach.  It should be able to encompass existing constructs, such regualr expressions.  I would also love to see it used to cleanup some of the existing ickier bits in Java.  Mathimatical expressions and string composition being at the top of the list.

Java can allow operator overloading, and I will use the feature in a similar manner to that of C++.  Or, Java can provide another way for me to define and use a limited DSL within the larger context of the language, and I would be more than happy to us it instead.  Or, Java can do nothing to address this need, and I will continue to dream of the possibilities.

Java is a GPL.  Can it also be an environment for building limited DSL's?  Should it be?  I would rather have a formal way to define and use little DSL's, and not have operator overloading.  But if no better option is available, then I will take operator overloading over nothing at all.


Submitted On 29-NOV-2006
jschell
Time to repeat it again...

The problem is NOT just that operator overloading can be misused.

The problem is that that the ADVANTAGE of adding it is more than offset by the DISADVANTAGE of the misuse.

Two parts, not one part.


Submitted On 02-DEC-2006
I am in total agreement with the post of 05-NOV-2006. Regarding maths, I would like to improve on my positions of 20-AUG-2006 and 24-AUG-2006. To have to define two classes for each type is definitely too much. We should abandon the buffer classes idea, and go for the immutable class mechanism. The hitch here is that it is not the way the String class is working. Ok, maybe we can change that, then. Let's see. Instead of having

String s = s1 + s2;

translated into

StringBuffer b = new StringBuffer(s1) ; b.append(s2) ; String s = b.toString();

, let's translate it into

String s = s1.concat(s2);

ok, that entails an object creation, which could cause performance problems. To escape that, we could just keep the StringBuffer around (we'll have to anyway for ascending compatibility...) and issue that it has to be used explicitely when one wants optimized string concatenations. The + operator will be reserved for cases where code readability is more important than performance.

That opens the way to a similar treatment of the arithmetic case. Let me re-state it:

public interface Arithmetic<T extends Arithmetic<T>> {
    T add(T t);
    T subtract(T t);
    T multiply(T t);
    T divide(T t);
    T negate(); // used for unary "-" (possibly)
    T pow(int n); // used for "^" or "**" (possibly)
}

Regarding collections, we could have:

List l;
l[i] = o; // l.set(i,o);
o = l[i]; // o = l.get(i);

Map m;
m[k] = v; // m.put(k,v);
v = m[k]; // v = m.get(k);

Note that in the set/put case, the operator being overloaded is not just [], but also the assignment operator =, which could make it not so simple to implement.


Submitted On 13-DEC-2006
dpieroux
Strongly support it.


Submitted On 12-JAN-2007
I am sick of the complains againist operator overloading because I guess none of you guys ever know how to exploit it or make big benefits from it.

I guess I have a solution for the operators priority problem.
one of you was saying the following is ambigeous

A^B*C+D

because the compalier most likely wont perform the the operations in the order that the programmer expect and hense leads to serious error.

thats make alot of sense 

however if the compiler force any overloaded operater to be solly inclosed by paranthesis (one to one) then the programmer will have more info about what he is doing like the following

(((A+B)*(B-C))^D)
the execution will start from inner most parenthesis and left to right:
1-(B-C) 
2-(A+B)
3-(*)
4- and finally the (^)

I guess this makes alot of clarity between the compiler and the programmer and the programmer must be able to understand this. Unless he is stupid programmer which the case we should not care about.

hopefully that will make sense

if you have application where you have long equations its so good to have the same look of equations as they are on the paper

plus we still need some math library like matrices or complex numbers ...... vectors...... alot of possibiltie

remember this is a general purpose language


Submitted On 12-JAN-2007
Operator overloading is great

I onced creat pool game in C++
it has alot of equations and vectors .. .. they were complex

and one of the things that help me debug well was that my equations on the papers matched my code so ........... that was great

if you supporter also please add to the following forum
that might help

http://forums.java.net/jive/thread.jspa?threadID=21349&tstart=15

I suggested very good contraint to make the operator overloading more bug 


Submitted On 24-JAN-2007
jwenting
Shame you can't vote against something. operator overloading is a disaster waiting to happen in any serious application that uses it.


Submitted On 13-FEB-2007
gilroitto
Voting against. 

Operator overloading just adds to the bastardness of a language. You can never quite be sure what your operation means - what if someone has changed the operator?


Submitted On 16-FEB-2007
I vote for operator overloading. It's very handy feature in other languages.

Python implemented them and it works wonderfully.  

C# implemented them (rather the functionality exists in the CLIand C# exposes a syntax similar to C++) and it has not devolved into the disaster that everyone makes out. 


Submitted On 21-FEB-2007
ivanlitovski
Vote for.

Doing serious mathematics in java is painful. People resort to (weka 3 code):

       double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
       Matrix A = new Matrix(vals);
       Matrix b = Matrix.random(3,1);
       Matrix x = A.solve(b);
       Matrix r = A.times(x).minus(b);
       double rnorm = r.normInf();

Operable interface suggestion from CliffNotes seems workable.


Submitted On 04-MAR-2007
pm_kirkham
In the three years since my last comment, the performance of the JVM and its handling of temporary objects has improved dramatically (well done), removing one of my stated concerns.

It may be possible to add sensible overloading for maths objects, based on introducing Ring and Field interfaces, and a guideline (preferably compiler enforced) which prevents the operators mutating the operands.

However, Java is not the only language for the JVM now, and with the release of the reference implementation of Fortress I'd expect that to be the choice for numerical work on the JVM. Fortress gives you any operator that can be written in unicode, which makes it far more flexible than C++ is - you can use 'ŰE;' to name the push operator to a monad, rather than reusing '<<".

I'd support extending the arithmetic operators for all the standard sub-classes of Number, and adding literal syntax for them and dates. But I don't see any need for confusing Java with facilities for general operator overloading.


Submitted On 04-MAR-2007
pm_kirkham
&#x219E; is unicode 219E, double headed left arrow, not sure what happened (can we not have a preview pane?).


Submitted On 11-MAR-2007
* Voting for *

I find it somewhat concerning that the community "prohibits" the natural development of the language, and I don't really think this should be a majority descision. It should be sufficient that a few of us greatly desire these features, for the rest of you; if you don't like it - don't use it.

I know this is a very rude statement to make, and I don't mean it as harshly as it may appear. I understand the concern about polluting the language and introducing bad coding practices. But I honestly believe that coding conventions should be implemented company wide, not world wide. Bad coding practices exist everywhere - even in Java. But bad code does not arise from what you "can" do, as much as "how" and "when" you choose to do it.

I would understand objections such as "it will break my 500.000 lines program and cause problems for all my customers", but this is hardly the case here, where we are adding a feature, not changing or removing a feature. I fully trust that that Sun can implement this in a way that doesn't break existing code.

Actually I'm quite surprised about most of the complaints that seems far too academic and pedantic to come from professional developers who have strict deadlines and productivity demands. Quality and maintainability is not meant to be handled by the programming language, it is meant to be achieved by responsible programmers, coding conventions, reviews and documentation. Besides, 95% of the bugs I handle is caused by misunderstanding what the program is intended to do, not grammar. I don't know about you guys?

True, new programmers will probably misuse this feature, like they misuse everything else. But before you complain about inexperienced programmers making mistakes, remember that you once were inexperienced too, and the *crap* that I am debugging right now, probably was written by one of you guys some 5 or 10 yars ago.

Being fairly new to Java, I can't pretend to be any authority on what is the most sensible grammar to use in this language to solve a specific problem. But I do understand, that if the language does not continuously develop and adapt to the market demands, new programmers, such as I, will quickly discard the language and stick to C++, C# or whatever background we come from. Eventually the language will wither and die, and surely that cannot be in anybody’s interest. So why not compromise a little with us ignorant C(something) morons? It's a small price to pay to get some fresh blood in the club, isn't it?


Submitted On 13-MAR-2007
_Roger_
Strongly disagree.

Operator overloading does not allow us to do anything that we can't do already. It's no big deal to have a method called add() to combine two objects. We don't need to overload the '+' operator.

Most operator overloading will end up being used for better  reason then because the guy that originally wrote the program thought it was cool. To a maintenance programmer it's a needless distraction.

Don't add features for the sake of it.


Submitted On 25-MAR-2007
verdyp
Vote against. But such feature may be implemented in a separate language that may then be preprocessed to generate Java source with method calls.

Use a custom preprocessor in your Java project, and you're done with it...

Note that the JVM is not supposed to run only Bytecode generated by a Java compiler. It will run any language that can generate compliant bytecode... And there already exists such languages compiling for the JVM, which may ease the development of numeric processing classes...

May be someone has a Fortran compiler for the JVM... Or APL or Lisp or Scheme or Prolog... be inventive!


Submitted On 13-APR-2007
I vote against it. It unnecessarily adds a source of error.


Submitted On 17-APR-2007
obsidian
Voting AGAINST.

This is a terrible idea. NO to operator overloading. 

It's the only thing worse than one-letter method names: reusing symbols already used for other things. And throwing in some order of operations goofiness for extra fun. 

So many years in the business... and just about every time I "see" (read: eventually discover after some painful episode) operator overloading was used, I inevitably find a mess in the code and a "hotshot" developer who needs some remedial training (or a career change). 

Everyone always gives the matrix algebra example. Know why there are so few other examples? There are so few other legitimate uses!

People who really are implementing math libraries do it in other languages. 


Submitted On 18-APR-2007
Against. 


Submitted On 19-APR-2007
philvaira
Include it. If Sun found a way to use it for readability (as Sun's code seems to suggest), then other developers will too. For those who find it so dangerous, they shouldn't use it if they don't know how to use it efficiently. 


Submitted On 04-MAY-2007
I am for operator overloading. This whole debate reminds me of whether "goto" is a bad thing or not (and before people start saying it is, remember that "break" and "continue" are gotos too - a rose by any other name and all that...)

The main reasons most people seem to be objecting are programmer abuse, readability and ease of maintenance. Here's some (constructive) criticism of those arguments followed by some reasons.

"Operator overloading can be abused."
True, but then so could the horn on a car; but no one ever said cars should not have a horn. Has no one ever heard of a peer code review? If you work in an environment with many other programmers then you absolutely must review each other's code. It's part of the development life-cycle in practically any software house. If you spot someone doing something that makes code unreadable or dangerous then say so. If they continually do it despite objections from everyone else then they should be fired. Simple as that (I've seen it happen.)

"I see a = b + c and don't know what it's actually doing with b and c without wading through the code."
This argument is wrong on soooo many levels. We all have nice IDEs that, with a couple of clicks of the mouse, will take us right to the definition of a method / operator. Even on those occasions when this feature isn't available (I still like to use VI from time to time because I'm a masochist :oD) it really does not take much effort to find the relevant bit of code. Alternatively, if the code for the class is not available and the documentation is lacking in details of what an operator is doing with it's arguments then this is a problem with the documentation, not the code or the language features used to implement it.

Besides which, you should have a good idea of what the code is doing anyway from context, comments, variable names, etc. (Contrived example follows!) Given

	Latitude lat1 = new Latitude("51°30'25\""); // London
	Latitude lat2 = new Latitude("48°52'0\""); // Paris

I would much rather see something like

	DeltaLatitude delta = lat1 - lat2;

than

	DeltaLatitude delta = lat1.calculateDelta(lat2);

Failing that, if the meaning of the code you are maintaining is so badly obfuscated that you really cannot tell what the heck is going on then there is something seriously wrong at the design level, not the language feature level. Again, this goes back to code reviews and even back to the architecture design stage. You can destroy the readability of code much easier with simple things like nesting too deeply or excessively long methods and classes long before operator overloading causes a problem.

"Operator overloading in language X sucks so I don't want it anywhere near Java."
So design it well! Duh!
 
"I can't tell if the semantics of this overloaded operator have been changed so it must be bad."
I could just as easily define a method called "add" in my class that simply throws away the data it has been given to operate on and returns random gibberish. I've changed the semantics of the expected behaviour of the word "add" and you would not know a thing about it until you tried to use the method. Again, this is just bad programming and bad documentation - nothing to do with operator overloading.

I could go on and on and on but anyhoo...

One last thing: Programming is an art form. An artist has many tools and methods to choose from to create their masterpiece. They will use the tools and methods appropriate to the job at hand. If they get the choice wrong it won't be a masterpiece. If they get the choice right it will be a masterpiece - talent excepted of course! The same holds for programming and restricting the tools and methods available to the programmer because some people make bad choices in when to use them stifles that creativity. Again, if the programmer does not have the talent to implement what they have envisaged then that's not the fault of the language or it's features, is it?


Submitted On 04-MAY-2007
operator overloading is a syntactic necessity for numerical computing. Java DP/WEB developers that insist that it is too "complicated" don't have to use it! Personally I would be happy if Java implemented the C# indexer and delagate concepts and added two new primitive types: a vector (compliant with the axioms of a linear space) and a complex number (fully compliant with the axioms of a field). Stop being stupid about this and just do it. Groovy already has!!!!


Submitted On 07-MAY-2007
xissburg
Its a must. I usually work with vector/matrix math and its is really hard to work with them without operator overloading. In C++ I have no problems at all. Well, I'm seeing that many ones are against adding this feature. Why? Because YOU dont need it? 'cause YOU wont use it?! do you think that after adding operator overloading to Java your application performance will get reduced?(Im sure it will not occur...). Then, all the features you dont need should be removed? is it that? I dont understand you...


Submitted On 07-MAY-2007
Against...in General..

though there are more things than matrix operations that I would think of it as useful...

ex1:   compareTo / Comparable interface..
would be nice if  2 instances of comparable could be used with < /  > operators directly.

ex2:  switch statement...
it would be nice if  switch would work with checking for the equals() method... so any object could be used with it...


so what I want is that Operators don't have to be definable by users  but it would be nice if they were defined on some more of the inbuild interfaces .. that  then could be implemented in a type where it is appropriate..


Submitted On 23-MAY-2007
Joe_h
I agree that operator overloading can make code difficult and unintuitive, but I think that the decision to use it should be left up to the programmer.  Please put it in.


Submitted On 07-JUN-2007
tschodt
 Submitted On 23-MAY-2007
Joe_h wrote:
> I agree that operator overloading can make code difficult
> and unintuitive, but I think that the decision to use it 
> should be left up to the programmer.  Please put it in.

You're missing the point.
Code must be maintained.
The best way to avoid encumbering maintainers with "difficult and unintuitive" code 
is to not allow exotic constructs in the language.


Submitted On 12-JUN-2007
kwutzke
When I once tried to learn C++, operator overloading was one of those things that I didn't really understand... so from a learning curve stand point I vote AGAINST that!


Submitted On 28-JUN-2007
i_program_java_all_day
Please, NO.  First of all, I think we should keep the language stable unless there is a dire need to change it.  We've gotten along fine without operator overloading for 10 years, which proves it isn't a necessity.  I agreed with Generics because they can provide a true reduction in bugs and a stronger-typed language, but even that feature is confusing developers to some degree.  This feature, on the other hand will cause both more bugs and in the end, even more confusion - not worth breaking code compatibilty.  Is it really that hard to pop-down an "add()" method in your IDE rather than typing "+".  I think the language is great like it is, although it maybe needs better standardization on AOP and Metadata/Annotations, decreased memory footprint, MVM, etc.  Too many other things are more badly needed.  As mentioned above, this makes me want a "Vote Against" feature for Bug Parade.


Submitted On 30-JUN-2007
invictus2
As far as I know this could lead to more object-types being usable in switch statements...and because of that fix the problem with switch statements being completly useless on Java.

I Vote for it


Submitted On 03-JUL-2007
Pro-overloading per the suggestion of CliffNotes waaay back when and mentioned by others in several posts since.

Make the binary operators aliases for methods:

A + B:   A.add( B )
A - B:   A.subtract( B )
A * B:   A.multiply( B )
A / B:   A.divide_by( B )
A == B:   A.equals( B )
A != B:  A.unequals( B )

And perhaps the <, <=, >, >= operators. The nice C-style +=, -=, *= and /= are then simply aliases for:

A += B:  A = A + B:   A = A.add( B )

etc.

Admittedly, this does heavily restrict how binary operators can be overloaded. I cannot fathom how one would abuse these other than making the 'add' method do something other than add, etc.

The rules for order of operation, commutivity, etc. are well-defined and unambiguous. The method supports strong typing without any casting problems or ambiguity problems not already faced by methods. People not wanting to use operators are free as they wish to use the expanded syntax.

As CliffNotes suggests, the methods may be included as part as an interface in java.lang.

I guess this would be a vote 'for'.


Submitted On 04-JUL-2007
A more general means of operator overloading might be to include a mechanism to define methods as aliases for operators.

Specifically, something along the lines of another keyword (I know, but hear me out):

public class T
{
public T myadd( final T rhs ) is +
{
    ....
}

public T myaccumulate( final int rhs ) is +=
{
    ....
}

public T thenegate() is - throws WhateverException
{
    ....
}

public boolean equals( final T rhs ) is ==
{
    ....
}
}

Some benefits of this approach:
- All operators are guaranteed to have a 1:1 correspondence with a method, and hence are associated with a named method. If the operator performs a wacky function, the method name will reveal it. If so desired, the developer can entirely avoid using operator syntax.

- Operator behaviour can be quickly and reliably checked for certain operands.

Specifically, the only return type allowed in the methods aliased to assignment methods += -= *= and /= (possibly |= and &=, etc.) is type 'T' for class 'T'. The compiler guarantees that all return statements in these methods are of the form 'return this'. In all cases, the compiler guarantees that all arguments are final. In the case of all non-assignment operators, including array access operators, ‘this’ and all data in its memory space is treated as ‘final’. The compiler disallows any use of the ‘this’ keyword anywhere inside the method body except for scope resolution or when passing ‘this’ directly as a ‘final’ argument to another method.

The methods aliased to '>= <= > < == !=' are verified to return type 'boolean'. Array access operators will accept only ‘final int’ arguments. The ‘= ! ~’ operators cannot be overloaded in any case. The binary operators are guaranteed to return non-void. If included in the spec, the post-crement and pre-crement methods are aliased to a single method with return type T and forced ‘return this’. In the post-crement case, the compiler transparently clone()s ‘this’ into a stack temporary prior to invoking the method, then passes the cloned copy out. As with ordinary variables, pre- or post-cremented objects are _illegal_ as l-values (i.e. no kludging: ‘A++ += 5’).

- In all cases, 'this' is assumed to be the lhs (or only) operand. 'this' might refer to a temporary object created by the compiler (as with the normal method syntax), but we don't care, since operators must follow normal l-value rules (i.e. no '(A + B) += C;'). This restriction also clears up the .toString() problem.

- A good deal of code can be easily modified by tacking on ‘is ...’ onto existing methods. This avoids having to duplicate method code for an operator or having to call the method from the newly added operator, which is inefficient. Likely, existing classes that would benefit from operators could be updated in a few minutes with no side effects, no extra methods or interfaces, and guaranteed 100% backwards compatibility. Admittedly, the ‘final’ declaration and illegality of ‘this’ for certain methods, if included, could hinder the process.

- Order of operations is known, strong typing is enforced. The scheme safely handles operators inside operators and (in all but the most contrived cases) self-operation (e.g. B = A + A).

The approach does _not_ address efficient operator chaining. It is not the most memory- or speed-efficient scheme suggested (though is guaranteed to be as good or better than method calls). The approach is still not iron-clad against ‘unoperatorlike’ side-effects in certain contrived cases, and it involves the addition of a keyword. It provides no facility for elegantly stating that a binary operation commutes between different data types (one writes separate methods for ‘A * B’ and ‘B * A’), nor can it support primitive types as LHS operands (one would have to write ‘A*2’ rather than ‘2*A’). Still, as far as striking a balance between flexibility and safety, it addresses many of the concerns voiced in this forum. C&C welcome.


Submitted On 07-JUL-2007
I support operator overloading whole heartedly.  To assuage the fears of the naysayers an operator overload could be tied to a method rather than being defined as it's own independent method.


Submitted On 17-JUL-2007
robert_engels
Please don't add this.

To all those that keep stating "well, I NEED IT, YOU DON'T..."  It has nothing to do with the fact that I don't need it. It has to do with the fact that MOST programmers cannot understand it, and will abuse it, and write horribly unmaintainable code.  Adding worthless features is not "growing the language".  The benefit has to be worth the added complexity, maintenance difficulties, etc.

I GUARANTEE that the the original designers of Java know far more about language development that any of the morons requesting this.

They left it out for valid reasons, not that they ran out of time (which was the case with generics).

If you truly need it, stick with C++.





Submitted On 20-JUL-2007
jschell
Time to repeat it again...

The problem is NOT just that operator overloading can be misused.

The problem is that that the ADVANTAGE of adding it is more than offset by the DISADVANTAGE of the misuse.

Two parts, not one part.

Miscellaneous points
- People never used it so they don't know how to use it. Answer: I programmed in C++ for 15 years I know exactly how it works.  And I know exactly how I and others abused it.
- It is needed for Math/Expressions.  Maybe.  But programs like that are a trivial part of what java programs are used for.  Java is used for real time programming is well and that need was met by creating a separate standard for real time java.  So do that if you want.
- Abuse should be controlled via coding conventions.  Which is a nice ideal.  Unfortunately in 99% of software development doesn't have any company policies at ALL that control that.  And of the remaining companies most do not in fact strictly enforce their policies.  So the remaining 0.0001% of companies that do that do not represent a case for the rest of the world.
- No new features means peope will use other languages.  This is one feature, not all features.  There is difference between adding new features and adding all new features.  And per the compared language of C++ note that the ANSI committee rejects many requests for new features.
- Programming is not a art that needs new tools.  Most artists never make money at all.  Programmers do make money.  Civil engineering allows for different looking buildings by using the same materials in different ways.




Submitted On 15-AUG-2007
If I had to summary this discussion, I would probably state that it is a fight between two main groups of people:
1)	People ‘against’: “Adding operator overloading would open the door to abuses. Keep it out of the language. Anyway, except perhaps for doing scientific computing, nobody needs that”.
2)	People ‘in favor’: “I would like to write readable numerical/scientific code in Java. (* Java is becoming fast enough to allow it and it is cross-platform… *). However, today the language forces me to write unreadable and obfuscate code”.

I guess that both positions are right. If the Java community is not interested by scientific computations that’s OK. Anyway the Fortran community is not interested in making Web applications either. And scientists and engineers have many other languages to choose from if they need operator overloading.

Thus, if it is in that direction that the Community decides to move, well its choice. But at least lets state it clearly: “Java is not targeting the scientific/numerical Community. You guys are kindly invited to choose a tool that fulfills better your needs. Java is not for you.”

However, if we are not ready to make such a strong statement, then yes, being able to define operators for user-defined types should be part of the language. And yes, it will be possible to write abusive code, as it is already today the case for most features of most programming languages (including Java) anyway.

To end with, if we look around us, it seems that currently most (all ?) dominant and successful languages allow operator overloading, with the notable exception of the Java programming language. How long can we stay in our Ivory tower claiming that, as far as operator overloading is concerned, we have seen the Light and the rest of the world is in the deep Darkness ? 


Submitted On 15-AUG-2007
d.pieroux
oups, my id does not appear on the previous post... It was written by dpieroux ;)



Submitted On 19-AUG-2007
Michael-Feldman
New point of view on Operator Overloading in Java

Operator overloading is a very hot topic. Everybody can find in the internet thousands of pros and cons. I agree with most of them. But we forget that Java contains operator overloading, e.g.

String s = “aaaa”;
int i = 20;

System.out.println(i+s); //compiler error
System.out.println(s+i); // will print aaaa20

As we see the current version of Java has operator overloading with confusing meaning. Additional examples may be: ‘|’, ‘&’ for integer and boolean and  ‘==’ for references.

In other side, we need something to write readable expressions for BigDecimals, Vectors, Complex Numbers etc.

I propose to stop discussion about operator overloading. Let’s discuss about operator declaration!!!! What does that mean? Don’t try to use same sign for operator (e.g. ‘+’ for integers and BigDecimals)! This is prohibited! Let’s declare new sign (e.g. ‘[+]’) for BigDecimals.

In other words we can declare algebra for BigDecimal numbers with operations:
[+] , [-], [*], [/] , [==], [<],[<=]  ….  (may be another notations)

Example:
BigDecimal bd = (bd1 [+] bd2) [*] bd3 [/] bd4;
if (bd1[<]bd3)
 . . . . . .

It seems a bit less readable then:

BigDecimal bd = (bd1 + bd2) * bd3 / bd4;
if (bd1<bd3)
 . . . . . .

but without any ambiguous meaning. 

 We can declare Algebra class for BigDecimal like this:

public class BigDecimalAlgebra
{
	@Operator(“[+]”, COMMUTATIVE) // bd1[+] bd2
	public static BigDecimal  sum(BigDecimal bd1, BigDecimal bd2)
	{
		. . . . 
	}
	@Operator(“[+]”,COMMUTATIVE) // e.g. bd1 [+] “279.25”
	public static BigDecimal  sum(BigDecimal bd, String str)
	{
		. . . . 
	}

. . . . 
}



Example of using: 
1. Whole class:
@Algebra(“BigDecimalAlgebra”)
public class MyClass
{
}

2. Single method

@Algebra(“BigDecimalAlgebra”)
public void calcSomething()….


3. Expression:
@Algebra(“BigDecimalAlgebra”) BigDecimal bd = bd1 [+] bd2;

Java compiler or preprocessor can interpret the sign ‘[+]’ depending on algebra annotation. 

That is idea. Of course, we need to define more accurate many-many details. I hope the idea can help us to add “operator declaration” to Java language and do not to destroy very fine language basis. Let’s discuss it.


Submitted On 14-SEP-2007
Reading the "operators as aliases for methods" proposals all I can say is *yuck*.  This really does not address the maintainability issues caused by operator overloading in any way.


Submitted On 21-SEP-2007
d.pieroux
I do not understand people rejecting operator overloading as a maintainability issue. Do they really think that everybody is developing the same kind of code for the same kind of applications all over the world?

Obviously, using in a wrong way any feature of any language leads to a maintainability issue. But, in the same vein, being forced to write unnatural code because the feature you need is missing leads _also_ to a maintainability issue. 

So please, do not use operator overloading if it is not the right solution for your problem. Use it if it is the right one. And if someone (a junior let’s say…) doesn’t know if operator overloading is the right or wrong solution for his/her problem, any senior can tell him/her: it is the wrong one.

So in conclusion: people asking for operator overloading are also very concerned by the maintainability of their code. That’s even one major reason for which they are requesting it. Its absence leads to writing unnatural code, which reduces the maintainability of their applications.


Submitted On 07-NOV-2007
Raniz
I'm completely for this.

What about adding a generic interface for each of the overloadable operators?
Classes implementing Addable<T,O> must
implement the method public T add( O other ) (where T is the class that implements the interface and O is any class which can be added to this class.
That solution will make it both type-safe and
controllable.
People will implement the method add( O other )
instead of operator+( O other ) which will probably
prevent a lot of people from making it perform some
stupid task and the compiler/jvm can just replace
"A + B * C" with "A.add( B.multiply( C ) ) provided that A implements Addable<A,B> and B implements multiplicable<B,C>. Standard operator precedence
must of course be preserved.


Submitted On 07-NOV-2007
if you really do a lot of math, and want readable code, use something like this.

Expression e = new Expression("a * b + (123.45 * c)");
Object result = e.eval(resolver);

With generics, that can even be improved.

The Expression can easily be cached, and/or converted to Java and compiled.

Doing this also allows for easy expression tracing, variable bounds checks, new operators, etc.

Anyone smart enough to say they can use operator overloading successfully (and understand others use of it), can easily write the above code.

It will also perform just as well as pure java code (if you compile and cache).


Submitted On 19-NOV-2007
d.pieroux
>> Anyone smart enough to say they can use operator overloading successfully (and understand others use of it), can easily write the above code.

Mmmm... Why should “someone smart enough” have to write an expression compiler if he can get it for free in virtually any other recent languages? => “Anyone smart enough” to do serious numerics or symbolic manipulation will thus choose a language that is better suited for his purpose and move away from Java. There are very good alternatives out there anyway.


Submitted On 27-NOV-2007
I'm completely for this.

Abusing is the matter of the user, not the rule.


Submitted On 02-DEC-2007
Psalm
I am in favor of adding operator overloading to Java, and have wondered for years why Java does not have it.  A great advantage of C++ and C# when working with complex variables or linear algebra, for example, is the ability to write an intuitively clear and concise a=b-c, instead of a=b.Subtract(c), which is no more meaningful.  


Submitted On 09-DEC-2007
Karaken_12
I vote against; the abuses that operator overloading can cause in C++ should be reason enough!  That aside, the Java paradigm has always been to use methods, and while implementing this RFE might not mean a great language change, it would violate this structure.  I for one would rather use something like
  MathVector u, v, w;
  w = v.add(u);
or
  w = MathVector.add(u,v);
than
  w = u+v;
simply because you know which method is being called on which object.


Submitted On 09-DEC-2007
Karaken_12
Specific response to xissburg:
Why are you arguing *for* operator overloading when you say you work with matrices?  To take a simple example, say you have two vectors u and v, and 'multiply' them:
  w = u * v;
Does this mean the scalar product, or the vector product?  Is w another vector, or a float?  The code is *not* self-documenting - it becomes ambiguous.  I see no reason that this should not be written
  w = u.vectorProduct(v);
other than to save a few keystrokes.  I find this much more comprehensible than the other way.


Submitted On 18-DEC-2007
The + operator is already overloaded for String because it is used *VERY* frequently. Java is also used very frequently for financial applications, so adding support for basic math (+ - / *) with BigInteger/BigDecimal is justifiable the same way. I don't care much for general overloading.


Submitted On 21-DEC-2007
I wish there were a way in the bug parade to vote AGAINST an RFE. The elegant simple language once known as Java already jumped the shark with the introduction of generics/annotations/boxing, and overloading operators will make even more obfuscated code possible. I am not against philosophically against generics, or even operator overloading (which helps make very elegant complex number and matrix classes), but I think the benefits of all these features need to be weighed against the overall impact to the language itself. If I want a language to include everything including the kitchen sink, I'll head back to C++ (or even C# once Microsoft jams in enough new language features). Let's just call Java finished and think about inventing the next new perfect language instead of grafting compromised solutions (like we got with generics) onto the existing infrastructure.


Submitted On 22-DEC-2007
Against if I wanted c++ I would program in c++.  This will just add need less confusion to java.


Submitted On 26-DEC-2007
Operator overloading should be provided ! Many times I have felt the need of this feature for example comparision of two objects, graphical  programs etc


Submitted On 03-JAN-2008
I strongly support the addition of operator overloading to Java, provided it can be done well. Among other things, it would decrease the differences between primitive and class types from the programmer's point of view, which would make both development and maintenance easier.

Pete Kirkham's argument that operator overloading blurs the difference between "the result of  x plus y" and "add x to y" does not seem to be accurate -- after all, we do have both + and += available.

And from an aesthetic point of view, there's really no good reason why primitive types can have 

a + b

while derived types have to have

a.add(b).


Submitted On 14-JAN-2008
d.pieroux
@ Karaken_12:
1) "because you know which method is being called on which object".

There is no difference in calling a method or a user-defined operator: in both case we end up calling a method. For instance, either you are calling the method 'add', whatever it does, or you are calling the method '+', whatever it does. This is just syntactic sugar, nothing to worry about.

And if you really want to know which method is called, better forbid dynamic dispatching at all, isn't it? Is it what you suggest?

2) You take as an example the vector product. This is one case where the '*' notation is ambiguous and should probably be not used. And so what? Are you balancing one specific case against all the other ones for which ‘*’ is well defined? Isn’t it throwing out the baby with the bath water?

Moreover, pushing a bit further your idea of protecting the whole world from writing “ambiguous” code, shouldn’t “times” be tagged as a forbidden method name in Java just in case someone would use it in his vector library? And what about the ‘add’ method of the Collection interface? Isn’t it a bit confusing for a collection of numbers? Why not to rename it ‘addElementAsCollectionMember’ instead to make its meaning clear? 

Writing software is a human activity and perfection will never be achieved. But at least let’s trust the people in their ability to make the good choices to solve their problems. And don’t believe that _we_ know better than _them_ what is good for _them_… Colonialism is over ;)


Submitted On 22-FEB-2008
johnno62
Not so keen on operator overloading myself but would be keen on the following syntactic sugar:

1) Variable x declared to be an instance of a class implementing java.util.List,
     x[i] could be compiled as x.get(i)
  and
     x[i] = y could compiled as x.set(i, y)

2) Variable x declared to be an instance of a class implementing java.util.Map,
      x{k} could be compiled as x.get(k)
    and
      x{k} = y could be compiled as x.put(k, y)


Submitted On 20-APR-2008
Martin.Strand
No!! The beauty of Java is its simplicity, if someone absolutely requires operator overloading then implement it as a preprocessor but for heavens sake don't let the Java language go down the same path as C++ where no two programmers' code looks the same.


Submitted On 22-APR-2008
jschell
-- 1. String concantenation is used frequently and Java is used for 
   financial apps frequently so operator loading should be added.

   Specious.

   COBOL, Fortran, Excel, C, C++, Basic and others
   are all used in financial applications.
   There are many, many types of applications which are not financial.
   The comparison of string concatenation to financial apps
   thus has orders of magnitude in difference.

-- 2. It is "helpful" sometimes.

   Pointers are "helpful" sometimes so why not add those to java?
   Explicit memory management is "helpful" sometimes so why not add that to java?
   Goto is "helpful" so why not add it?


-- 3. People will use another language besided java because of this.

   Obviously nothing but a subjective statement.

   The most common reason for choosing a language is preference anyways.
   So based on that argument java should have absolutely every other
   feature of every other language in the world.  And support every
   programming idiom as well (such as procedural.)

   Otherwise they might use something else.


-- 4. Java already has operator overloading because of the the '+'
thus it should be added.

   The String concatenation operator is NOT an example
   of an overloaded operator.

   C++ doesn't claim that the '+' operator is overloaded
   when one adds a int and float yet it still works.

   Perl doesn't claim that the '.' operator is overloaded
   when one concatenates two strings together yet is still works.

   C++ SPECIFICALLY defines string concatenation in terms
   of operator overloading.

   This sort of statement merely demonstrates that the
   reader is incapable of understanding differences in languages.


-- 5. Obviously posters here still do not understand the abuse argument.
   
   There are TWO parts to it.
   1. It will be abused.
   2. Compared to the legitimate use the illegimate
      use will FAR exceed the legitimate cases.


Submitted On 04-MAY-2008
Philip_S
Personally, I think that < > <= and >= should be overloaded such that 
    foo < bar 
is equivalent to
    foo.compareTo(bar) < 0
and likewise for the other three operators. Equality could possibly use === as the operator, but something else may be preferable.
kaffiene's suggestion of 20-SEP-2004 seems reasonable for other operators,  with the following rules:
    1) foo + string is always equivalent to foo.toString().concat(string), and likewise string + foo is string.concat(foo.toString())
    2) primitives may form one argument to an operator. (This is intended to allow complex numbers, bignums, vectors/matrices and so forth be used clearly in formulae.)  
    3) with these exceptions, operators can only operate on two instances of the same class, but may return anything. (This is intended to prevent the most egregious abuses, while still allowing dot product or similar operators.)

There could be a case for allowing + to be used to append an item to a collection (foo + collection adding at position 0, collection +foo adding to the end), but this leads to problems with the += operator, and leads to a slippery slope.

The precedence of prefix or postfix operators should be higher than anything else (matching the behaviour of ++ and unary -) but infix operators would need to have their precedence specified, or all have equal precedence, lower than "natural" (non-overloaded) arithmetic operators but higher than comparison operators.


One final point regarding kaffiene's suggestion is that the Operator keyword is redundant, as infix, prefix, and postfix would be sufficient to identify the operator function as such.


Submitted On 10-MAY-2008
DWilches
I think we shouldn't un-constrain as much the Java language as we could. I think that the lack of operator overloading, properties (C# like getters and setters), structs, switch on strings, syntactic sugar, and all those things that developers are used to see as programming languages features is getting attention out from Java to C# or other more syntactic sugar languages.

Some of this features could be created by the add of syntactic sugar: not changing the Java bytecode language, but the compiler's understood language.


Submitted On 04-JUN-2008
tinyweldingtorch
Against adding it.


Submitted On 22-JUN-2008
I am in favor, actually i am in desperate need of it.

All the against arguments are about maintain problems because of uncertain results if operator overloaded. In the other side all the supporters are concentrate to the easy of writing and reading calculations. So far you can say that safety is more important than convenience  but actually the lack of convenience drives to the lack of safety.
 
Let say that try to maintain or to extend some other code. follow are two examples.
double length = 100; // miles
double time = 20 ;// seconds
double speed = length / time; // miles per second
Nice and clean. Only if you check all the code to be sure about the units.

Length l = Length.miles(100);
Time t = Time.seconds(20);
Speed s = l.div(t);

The second example is absolutely safe under any circumstances (unless the developer is idiot and make bad implementations of Units Classes).But nobody are going to use it in more complex equations because it is not convenience to write and hard to read. So we ended with uses of first example and we found that somebody use wrong units after we lost the spaceship in the outer space.
Safety of a language is not about to protect the developer from his stupidity (you can't) is about to protect him from unpredictable results.
Because in applications very rarely we use just numbers, in most cases we use amounts and is critical to have a built in safety that we don't add apple with oranges.

I don't know if the solution is operator overload in general or specific to numbers or what else but it is absolutely inevitable to have some infrastructure to help us to work with amounts not only with numbers. 


Submitted On 30-JUN-2008
jGardner
"postOffice += message" may be ambiguous, but gee, I think postOffice.mystery(message) is ambiguous too... Why does Java allow me to name a method 'mystery'? or 'doSomething' !?   or postOffice.a(message);

In my opinion, methods should be banned because it is too easy for a programmer to name their method something someone else won't understand.

That's basically what you are saying.


Submitted On 11-JUL-2008
I am strongly opposed to adding operator "overloading" in Java. However, I do think there is a strong argument to made in favor of adding something like operator "definition". I.e., don't allow the currently defined operators to be overloaded, but do allow new operator symbols to be defined for a particular scope, then used as a syntactic replacement for the usual infix work-arounds. There are issues to be worked out in this approach, but I think this would represent a compromise that could make both camps in this discussion happy.

First, all the current operators in Java retain their current meanings and rules, so no confusion is introduced by having to relearn what an old symbol means in a particular context. 

Second, there needs to be a mechanism to create a new operator that can be parsed by the compiler and recognized as an operator. Under the covers, there's no reason why the compiler can't continue using infix method call syntax as is normally done, so

A {plusSymbol} B is still rendered in bytecode as a.plusSymbol(B) would be.

As far as the mechanism for defining new symbols, there have been several suggestions above to use Unicode characters. I think this idea has promise. It will be easier once something like UTF-8 (at least) is the default, standard encoding on all platforms, including source code files. This is not a trivial migration, however. But for those who want to make use of this feature, mandating they use UTF-8 in their source files and IDEs/text editors that support them seems reasonable.

Also, as replacements for the standard operators (which are not being overloaded), we'd have to make sure the fonts/glyphs used to represent them are clearly different enough to avoid confusing them with the standard +, -, *, etc. But they would also have to look familiar to domain experts using them, so a plus symbol, although visual distinct from the standard java + operator, still looks like a "plus" operator. But this also has advantages. For example, a multiply symbol that looks like a dot halfway up the line, like you see in math textbooks, could be represented properly without having to use the "x" character or "*" as a hack. You could also render the glyphs with certain "badges" so a dot product symbol would be visually distinct from the vector product symbol, etc.

I would imagine syntactically you'd define these operators with the existing Java idioms, perhaps introducing a single new keyword "operator", so as you now define a class as 

class Foo {

{access keyword} {return type} {method name} ([argument list]);

}

you'd define an operator as

operator + {

{access keyword} {return type} {method name} ([argument list]);

} 

The plus sign above would actually have to be a Unicode character whose glyph represented the symbol you wanted to define, something that looks like a plus sign but is also visually distinct from the standard + operator glyph. The return type would represent some base type that is returned from evaluating the implementation method/expression. You'd have to allow primitive types as well as reference types here. The access keyword would allow you to scope the operator, so you could keep it private to a class or package for example. The method name would work like it does in C++, giving you a way to define a standard method to implement the operator's functionality. The argument list would let you specify the types of arguments the operator can operate over. Issues about symmetry, transitivity, etc, would have to be worked out. And perhaps you would be able to specify overloaded versions of the implementation method, so that you could define rules for the operator when it's used in a unary, binary, or tertiary context, etc.

The more I think about this approach, the more I think it can address the concerns of both camps.


Submitted On 16-JUL-2008
I am in favor,


Submitted On 18-AUG-2008
I know most people don't consider VB a language but have any of you seen how operator overloading is implemented by VB.NET? "In VB.NET (and C#) overloaded operators must be shared (static), and operator methods must have the same count as the operator you are overloading. Finally, in VB.NET the special word Operator is used in place of Sub or Function, which makes it very clear that the method you are looking at is an operator statement."

I think of it's syntax like this:

   [public?] static Distance operator +(Distance a, Distance b) {
      // Some code here...
   }

or even like this (names should be standardized)

   operator Distance add(Distance a, Distance b) {
      // Some code here...
   }

I prefer the second solution as it looks more Java-like.

Everyone should understand the compiler must enforce at least one parameter in the overloading method should be of the declaring class (or you could declare a new way of adding two integers). Allowing the order of the parameters to make a difference is up to Sun (or another voting). Plus, it could be allowed to work just like generics works today: just a compiler-time sugar; the underneath class file remains simple with regular methods and the compiler replaces operator calls with regular method calling. Previous JVMs would just see a static method; compatibility is kept.

Operator overloading is harder in C++ because C++ supports overloading tricky operators like member-of (.) and function call () -- which could help implementing AOP. In addition, C++ supports static and instance operators, which is not the intended case.

Also, I believe the real problem resides on the developer who learns something new and quickly want to employ it in every code s/he touches. People need a little discerning about when to use operator overloading and when not to use. You don't like it, don't use it. And tell your company not to use it too. Simple as that.

So, I'm in favor.


Submitted On 04-SEP-2008
Another vote AGAINST this.


Submitted On 17-SEP-2008
dkane1
Against. Never needed that since the first version of Java and in many projects. No benefits, but additional code complexity. 


Submitted On 13-OCT-2008
Against


Submitted On 19-NOV-2008
eadward
Against. I've done commercial, financial, graphical and academic applications. I worked with juniors and seniors. I programmed with C, C++, Java and a lot of other languages. Operator overloading never helped me.

Even the string concatenation is a bad habit, since "a = b + c" is compiled as "a = new StringBuilder().append(b).append(c).toString()". Put that on a huge loop and your application slows down.

The biggest problem is: what does operator means? If you are dealing with numbers, the one-and-only-universal math tells you what it means. But, if you are dealing with objects, only God knows what it means.

Seems more like laziness to me.


Submitted On 29-NOV-2008
bestsss
for over 20 years programming I can recall single time I'd need such feature. I don't even see how it helps the language


Submitted On 11-JAN-2009
David_Krutsko
Although code can get harder to read, properly structured and commented should make no problems.


Submitted On 10-FEB-2009
I like the circled operator suggestion.  It's less likely to be abused.  Also I liked the suggestion to use interfaces to implement this.  But on balance, I think I don't like this idea.  But if you do do it, please do it nicely.


Submitted On 25-FEB-2009
chaos06
Against. 


Submitted On 05-JUN-2009
quintinbeukes
Against. 

This is my opinion on this matter. One of Java's "winners" is it's elegant design which leads to clean and well understood code. Even though this sometimes requires more round-about ways of doing things (like .add() or .plus() instead of +). Operator overloading is a sure way to start a slow polution of the public code out there. 

One should be careful to not over complicate the language itself. Simplicity is sometimes the best option, and I believe Java's simplicity (relative to C++'s amazing complexity) makes it score many points in clean/well structured code. I have found it much easier to get to grips with an open source Java project's code than with a C++ one, mainly due to this. 

Giving people to much to work with often leads to abuse. Taking the stance of "but then they aren't using it the way it was meant to be used" isn't valid IMO. People will use it wrong, and this will cause polution. Operator Overloading is very sensitive, and needs to be applied carefully. And if it's there, many people will use it simply because they feel it fits the solution. In a Simplicity Model you reduce the chances of people taking this route.


Submitted On 04-OCT-2009
zeratulok
Against.


Submitted On 04-NOV-2009
TomPasTom
As a beginner I must add my commentary.
I've been programming both Java and C/C++ and obviously Java's architecture is way more defined as "keeping us from hurting ourselves".
it is also much easier to debug (even though not so easy !!!) a code written in Java no matter how complex the code itself is.
However, I think that Sun should consider adding operator overriding to Java from many reasons, but the main one is it just make sense.
As programming languages go forward (very slow I should say...) towards helping programmers program "The Real World" it is very logical to add Vector Objects for instance, as VecA + VecB will simply add the respective fields of each Vector. There are tons of examples where it make sense to use many operators such as comparison between two objects.
So why not adding this feature to the language ?!
I think programmers can benefit many ways, while not really hurting pure object oriented programming and Sun's philosophy.
 



PLEASE NOTE: JDK6 is formerly known as Project Mustang