Java ‘+’ operator between Arithmetic Add & String concatenation? [duplicate]

This is basic operator precedence, combined with String concatenation vs numerical addition.

Quoting:

If only one operand expression is of type String, then string
conversion (§5.1.11) is performed on the other operand to produce a
string at run time.

The result of string concatenation is a reference to a String object
that is the concatenation of the two operand strings. The characters
of the left-hand operand precede the characters of the right-hand
operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a
constant expression (§15.28).

An implementation may choose to perform conversion and concatenation
in one step to avoid creating and then discarding an intermediate
String object. To increase the performance of repeated string
concatenation, a Java compiler may use the StringBuffer class or a
similar technique to reduce the number of intermediate String objects
that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the
creation of a wrapper object by converting directly from a primitive
type to a string.

See language specifications here.

TL;DR

  • Operator precedence for + is from left to right
  • If any operand in a binary operation is a String, the result is a String
  • If both operands are numbers, the result is a number

Leave a Comment