This question already has an answer here:
I saw this question a few minutes ago, and decided to take a look in the java String class to check if there was some overloading for the +
operator.
I couldn't find anything, but I know I can do this
String ab = "ab";
String cd = "cd";
String both = ab + cd; //both = "abcd"
Where's that implemented?
Most of the answers here are correct (it's handled by the compiler, + is converted to .append()...)
I wanted to add that everyone should take a look at the source code for String and append at some point, it's pretty impressive.
I believe it came down to something like:
=
But then some magic happens. This turns into:
Whereas most people believe that it will create "ab", then throw it away when it creates "abc". It actually understands that it's being chained and does some manipulation.
There is also a trick where if you have the string "abc" and you ask for a substring that turns out to be "bc", they CAN share the exact same underlying array. You'll notice that there is a start position, end position and "shared" flag.
In fact, if it's not shared, it's possible for it to extend the length of a string and copy the others in.
Now I'm just being confusing. Read the source code--it's fairly cool.
It's done at the language level. The Java Language Specification is very specific about what string addition must do.
String
is defined as a standard type just like int, double, float, etc. on compiler level. Essentially, all compilers have operator overloading. Operator overloading is not defined for Developers (unlike in C++).Interestingly enough: This question was logged as a bug: http://bugs.sun.com/view_bug.do?bug_id=4905919
The compiler treats your code as if you had written something like:
Edit: Any reference? Well, if I compile and decompile the OP's code, I get this:
So, it's like I said.
This is special behavior documented in the language specification.
From the Fine Manual:
See String Concatenation in the JLS.