0

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");
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66
Parthasarathy
  • 308
  • 2
  • 10
  • `(c+1)`, don´t forget paranthesis, otherwise after the first operation `"here ..." + c...` everything else will get handled as `String` concatination. – SomeJavaGuy Oct 13 '16 at 05:34
  • The expression you wrote is equivalent to `((("here the problem " + c) + 1) + " Case")`. This is called left-associativity. – ajb Oct 13 '16 at 05:52

3 Answers3

2

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"
nbrooks
  • 18,126
  • 5
  • 54
  • 66
1

Try this

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

As this always try to evaluate the expression in the parenthesis before string concatenation

Noushad
  • 384
  • 3
  • 11
0

It's not a matter of how System.out.println works. Java treats your statement as concatenation. Because when you use + with string other variable will be treated as string and java will perform concatenation

Anthony
  • 116
  • 8