14

Java does not have concept of operator overloading.

Still + operator behaves as addition operator with numbers and concatenate operator with strings. This is similar to the operator overloading behavior.

So, does Java have operator overloading?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Abhishek Jain
  • 6,296
  • 7
  • 26
  • 34
  • Java libaries are written in native code ie C/C++. Please correct me if I am wrong. As C++ supports operator overloading, did Java creators use this functionality for + operator? This is just a guess. Please correct me. – Abhishek Jain Jun 02 '10 at 07:23
  • 1
    Re your comment: No, probably not. I highly doubt it was something simply passed down from C++; it was a conscious decision. – Sasha Chedygov Jun 02 '10 at 07:50
  • 3
    @Abishek: the JVM can be implemented in any language, which may or may not support extra-linguistic operator overloading. – polygenelubricants Jun 02 '10 at 07:52
  • 6
    @Abishek: Most classes of the java libraries are written in java only the jvm and the classes interfacing with the operating system are written in native code. Also operator overloading is only a compiler trick, in c++ adding string a and string b like this "a+b" is only a short way to call the function "a.operator+(b)", in java "a+b" is a short way to write new "StringBuilder().append(a).append(b).toString()". Both are implemented in the compiler only. – josefx Jun 02 '10 at 08:20
  • possible duplicate of [How does the String class override the + operator?](http://stackoverflow.com/questions/11408427/how-does-the-string-class-override-the-operator) – Pooya Oct 04 '14 at 06:29

9 Answers9

16

It's basically operator overloading - just built into the language.

"Java does not have concept of operator overloading" is only true inasmuch developers cannot overload operators.

The language spec can, and strictly speaking, all the arithmetic operators are overloaded to handle calculations that involve more than one numerical type. And even there, it sometimes creates confusion (such as having to cast one operand to double if you want a divsion of int values to yield fractional results).

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
13

Does the Java language overload some operators?

YES! As you've found out, the operator + can mean two different things, string concatenation or numeric addition. This is, by definition, an operator overload.

Here's the list of all Java operators:

JLS 3.12 Operators

The following 37 tokens are the operators, formed from ASCII characters:

  =     >     <     !     ~     ?      :
  ==    <=    >=    !=    &&    ||     ++     --
  +     -     *     /     &     |      ^      %     <<     >>    >>>
  +=    -=    *=    /=    &=    |=     ^=     %=    <<=    >>=   >>>=

Some of those operators are overloaded. Here are some examples:

System.out.println(   3 + 4 + "X"     ); // prints "7X"
System.out.println(   3 + (4 + "X")   ); // prints "34X"
System.out.println(   "X" + 3 + 4     ); // prints "X34"
System.out.println(   "X" + (3 + 4)   ); // prints "X7"

System.out.println(0 == 0);                           // prints "true"
System.out.println(new Integer(0) == new Integer(0)); // prints "false"

System.out.println(true & (1 & 2) == 12); // prints "false"

Can we overload the operators defined in the Java language?

ABSOLUTELY NOT! All Java operators mean exactly as specified by the language specification. There is no "extra-linguistic" semantics: a Java operator can NEVER do something that isn't specified by the language.

That is, unless the language changes, the following are guaranteed truths:

  • someString + whatever is ALWAYS string concatenation
  • referenceType == anotherReferenceType is ALWAYS reference equality
  • No funky things like 3 * "a lady" or "my heart" / 2 or even 10**3 ~= 999

As the above snippet shows, however, even the current state of operator overloading can still be quite confusing, especially for beginners. By not allowing extra-linguistic overloads, at least this confusion is limited: once a programmer learns about what all the operators in the Java language do in various overloaded scenarios, their exact semantics in all Java code becomes clear and precise.

Operator overloading can be quite confusing. Some think that it's "bad" enough as it is. To allow users to overload the Java operators to do something outside the language specification can only lead to even more confusion.

Here's an excerpt from Java Puzzlers, Puzzle 30: Son of Looper:

The lesson for language designers is the same as [two other puzzles]. Operator overloading can be confusing. Perhaps the + operator should not have been overloaded for string concatenation. It may well be worth providing a string concatenation operator, but it doesn't have to be +.


Do you need C++ to support operator overloading in Java?

NOPE! This has nothing to do with it at all. All that the Java compiler needs to do is parse the program source code according to the grammatical rules of the language, and determine, for each operator, what the types of the operands are. This information is enough to deduce what the meaning of the operator is, and to then act accordingly as specified by the language.


Appendix

JLS References

Revealing questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
10

The + operator IS overloaded. Java just prevents YOU from overloading it yourself.

Khan
  • 2,912
  • 3
  • 21
  • 21
5

Concat operator is a special support provided in Java. A quote from Javadoc below.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuffer class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

For information, see this

bdhar
  • 21,619
  • 17
  • 70
  • 86
  • 1
    actually, in current java versions it's StringBuilder not StringBuffer: http://java.sun.com/javase/6/docs/api/java/lang/String.html StringBuilder is the non-synchronized version of StringBuffer and usually faster (thread safety is not an issue in string concatenation) – Sean Patrick Floyd Jun 02 '10 at 08:17
4

The polymorphic treatment of operators in Java is a form of operator overloading, as that term is traditionally used. For example, read the wikipedia page on operator overloading, and you will see Java style of overloading mentioned in the first paragraph.

"In computer programming, operator overloading (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments. Sometimes the overloadings are defined by the language; sometimes the programmer can implement support for new types."

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    +1. Re: "Sometimes [...]; sometimes [...]" is the key distinction here. Java language overloads MANY operators, but there is no extra-linguistic operator overloading. All operator overloadings are just what the language defined, nothing more. – polygenelubricants Jun 02 '10 at 07:48
0

The functionality you are talking about is just built-in in Java. You still don't have control on operator overloading.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
0

Java does not allow programmers to overload operators, but has built-in support for operators on some of its built-in types (I think String is the only object with support for any operator, other than auto-boxing stuff).

abyx
  • 69,862
  • 18
  • 95
  • 117
0

There is no operator overloading in Java, in the sense that the programmer can't overload any operator himself. However, the Java language has some kind of integrated operator overloading, which assigns different behaviors to the + operator, depending on the context.

The operator gets compiled into different bytecode instructions, depending on the operands:

For String "addition", a StringBuilder is created and used behind the scenes

For int addition, the JVM command iadd is used.

For double addition, the JVM command dadd is used.

etc...

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
0

I feel this behaves more like implicit conversion of one type to another than like operator overloading.

Peter Tillemans
  • 34,983
  • 11
  • 83
  • 114
  • Implicit conversion of what to what? There is no conversion going on there. You don't convert numbers to strings when you add them, or vice versa. – Sasha Chedygov Jun 02 '10 at 07:51
  • 2
    No but Java converts numbers to strings when you concatenate them. Java converts other objects to strings by invoking the toString method. Integers and int are now autoboxed and unboxed. These are all "implicit" conversions in my view. – Peter Tillemans Jun 02 '10 at 07:56
  • It's operator overloading, whose implementation *sometimes* does implicit conversion, when used on disparate types. But as Eyal wrote: int+int is a different thing than double+double or String+String, yet there is no conversion involved. – Michael Borgwardt Jun 02 '10 at 08:05
  • But a conversion will take place if we write int + string. – Nrj Jun 02 '10 at 09:58
  • @Michael Aahhh, now I get it! Thanks for giving me this flash of insight. I never though about int+int and double+double as operator overloading, but you are absolutely right : it actually is! – Peter Tillemans Jun 02 '10 at 11:07