Parthasarathy Parthasarathy - 9 months ago 74
Java Question

System.out.println +(plus ) is doing concatenation insider of incrementing

Hi friends am new to java when am processing through the loop i want to show the loop counter value increment by 1. when i kept the below code of that am getting the value as like of concatenate with 1 with the counter value. How the System.out.println is working with concatenate and addition.

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


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"