0

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?

Surendra
  • 29
  • 3

2 Answers2

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130