Can any one tell me the exact implementation of '+' operator of String in Java. As I know this is concat operator to concat two string even then since String is a class then where is implementation of this operator and how it works?
-
2See this SO question for your answer: http://stackoverflow.com/questions/11408427/how-does-the-string-class-override-the-operator – JREN Jun 25 '13 at 07:20
-
See this: http://stackoverflow.com/questions/2328483/operator-for-string-in-java – Darshan Mehta Jun 25 '13 at 07:21
-
Try this : http://docs.oracle.com/javase/tutorial/java/data/strings.html – newuser Jun 25 '13 at 07:23
2 Answers
The implementation is compiler-specific, although it usually just ends up creating a StringBuffer
or StringBuilder
behind the scenes, and appends to it. Note that it has special treatment for efficiency, so that x + y + z
can be compiled as something like
new StringBuilder().append(x).append(y).append(z).toString();
... and also to perform compile-time concatenation of constant string expressions.
You can see the operator described in JLS section 15.18.1, but that doesn't mandate any particular implementation.
To see what your particular compiler does, simply compile some code you're interested in and then use javap -c
to look at the bytecode it generates.

- 1,421,763
- 867
- 9,128
- 9,194
String +
may be optimised away by the compiler. If it is not it is the same as
a + b
becomes on most JVMs today (older versions used StringBuffer)
new StringBuilder().append(a).append(b).toString();
So StringBuilder.append() is what you want.

- 525,659
- 79
- 751
- 1,130
-
1This depends on the compiler. The JLS allows the compiler to code generate this in other ways. – Stephen C Jun 25 '13 at 07:28