Java Reference ยท Operators
Java string concatenation with +
Reference for Java string concatenation with + and +=: how operands are converted, evaluation order traps, null handling and when to use other tools.
When either operand of + is a String, Java does not add: it converts the other operand to text and joins the two. Primitives are converted as if by String.valueOf, objects by toString(), and null becomes the text "null". The same applies to += on a String variable.
+ is the only operator Java overloads for a library type. Everything else about strings, such as concat(), join() or StringBuilder, is ordinary method calls.
String msg = "Total: " + 3 + " items";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
String result = left + right; // at least one operand is a String text += other;
| Operand type | Converted with |
|---|---|
| primitive | String.valueOf(value) |
char |
the single character (not its code) |
| object | String.valueOf(obj), which calls toString() |
null |
the text null |
| array | its type and identity string, not the contents |
Usage notes
- Left to right.
1 + 2 + "a"adds first,"a" + 1 + 2concatenates twice. Use parentheses when you want arithmetic inside text. char + charis addition.'a' + 'b'is theint195. Put a string in front or useString.valueOf.- Compile-time constants (
"a" + "b", orfinalvariables with literal values) are joined by the compiler and interned. - Performance. A single expression such as
a + b + cis compiled efficiently (since Java 9, withinvokedynamic). Repeateds += xin a loop copies the string each time and is quadratic; build withStringBuilderinstead. See StringBuilder. - Arrays print as
[I@...; useArrays.toString()orArrays.deepToString(). - Null-safe.
nullnever throws here, but calling.toString()on it does. - Formatting alternatives:
String.format,formatted(),String.join, text blocks, andStringJoinerhandle layout and separators better than long chains of+.