Search code examples
javastring-concatenationoperator-precedence

Additive Operator (+) Performing Concatenation Instead of Addition


I am new to Java. When I am processing through the loop below I want to show the loop's counter value being incremented by 1. When I kept the below code of that I am getting the value as like of concatenate with 1 with the counter value. Why is the System.out.println working with concatenation instead of addition?

for (c = 0; c < Size; c++) {
  System.out.println("here the problem " + c+1 + " Case");
}

Solution

  • The + operator is overloaded for both concatenation and additon, and both operators have the same precedence, so the operations are evaluated from left to right.

    Starting at the left, the first operand encountered is a String "here the problem", so the operator knows that it should perform concatenation. It proceeds to concatenate c to that String, yielding a new String.

    The second + therefore is operating on that resulting String, and 1, so once again it does concatenation.

    If you want to specifically control the order of the operations, and have c + 1 evaluated before "here the problem" + c then you need to enclose the operation in parentheses:

    "here the problem " + (c + 1) + " Case"