1

This question states that Java has no operator overloading. An answer to that states that "a" + "b" is possible even if that really looks like an overloaded +. My question is simple: if + can only ever sum numbers and it cannot be overloaded, how can "a" + "b" (string + string) possibly work?

Community
  • 1
  • 1
Caridorc
  • 6,222
  • 2
  • 31
  • 46
  • Because that's the way the Java creators made the language... there's nothing you can do to replicate that same behavior – Michael Sep 20 '15 at 21:49
  • @Michael many things that you see in a language you can implement yourself, so I wondered how I could implement this overloading if not others – Caridorc Sep 20 '15 at 21:52
  • There is no programmatic operator overloading. But some operators are defined with a dual meaning: `+` for addition and `+` for string concatenation, `^`,`|`,`&` for bitwise operations, as well as for logical operations. – RealSkeptic Sep 20 '15 at 21:52
  • Sadly (or maybe, if you hate operator overloading: happily), you cannot. This is a built-in feature of the language @Caridorc – Michael Sep 20 '15 at 21:53
  • @RealSkeptic _But some operators are defined with a dual meaning_ that seems impossible without overloading, or maybe you are telling me that operators cannot be overloaded, with the arbitrary exception of string + string and ^ & | for logic & bitwise ? – Caridorc Sep 20 '15 at 21:55
  • Yep, that's exactly what I'm telling you. There is no programmatic operator overloading (the programmer cannot give operators new meanings), but the syntax of the language uses a few specific operators differently in different contexts. – RealSkeptic Sep 20 '15 at 21:57
  • @RealSkeptic thanks, all is clear now. Java designer surely followed the principle of most surprise. Either a thing can be done everytime or never at all, not just in 1 or 2 arbitrary places. – Caridorc Sep 20 '15 at 21:58
  • Sorry everyone for the dupe, I should have searched more, you gave me good info anyway :D – Caridorc Sep 20 '15 at 22:01

1 Answers1

1

According to JavaDoc

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 StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.

ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42