Skip to content
Tutorials Center
My learning

Topics

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.

Java
String msg = "Total: " + 3 + " items";

Try it

Java Evaluation order

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.

Java Concatenation versus alternatives

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

Java
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 + 2 concatenates twice. Use parentheses when you want arithmetic inside text.
  • char + char is addition. 'a' + 'b' is the int 195. Put a string in front or use String.valueOf.
  • Compile-time constants ("a" + "b", or final variables with literal values) are joined by the compiler and interned.
  • Performance. A single expression such as a + b + c is compiled efficiently (since Java 9, with invokedynamic). Repeated s += x in a loop copies the string each time and is quadratic; build with StringBuilder instead. See StringBuilder.
  • Arrays print as [I@...; use Arrays.toString() or Arrays.deepToString().
  • Null-safe. null never throws here, but calling .toString() on it does.
  • Formatting alternatives: String.format, formatted(), String.join, text blocks, and StringJoiner handle layout and separators better than long chains of +.