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

Solution 1:

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

Solution 2:

This isn't to do with string concatenation per se. It is about implicit casting to String. And it operates left to right, without implicit parentheses in the cases above. And String takes precedence over int.

Example 1

System.out.println("3" + 3 + 3);

Here, it begins with a string, so each operation after that is implicitly cast to string before doing the + operator. Hence, "333".

Example 2

System.out.println(3 + "3" + 3);

Same applies here, as the String takes precedence over the initial 3.

Example 3

System.out.println(3 + 3 + "3");

In this case, the first two numbers are added as they are ints, resulting in 6, but as it gets added to a String next, then it assumes concatenation, hence "63".

As per specification.

Solution 3:

Precedence of evaluation for + is from left to right and this is how it works:

  1. System.out.println("3" + 3 + 3);
    When you try this, since the first parameter is a String, everything rest will be a String concatenation

  2. System.out.println(3 + "3" + 3);

    Same goes for this one, because you cannot add first int 3 to String 3 and then last 3 will be concatenated to second 3

  3. System.out.println(3 + 3 + "3");

    First left to right expression is evaluated (giving 3+3 = 6) and then string 3 is appended to result of that evaluation giving 63 as output