[Solved] Increment operator java [closed]


Because you’re using the post-increment operator ++ that occurs after the variable to increment. Its value is the current value of the variable, and the increment happens afterwards.

JLS 15.14.2 covers this:

[T]he value 1 is added to the value of the variable and the sum is
stored back into the variable.

and

The value of the postfix increment expression is the value of the
variable before the new value is stored.

It does get incremented — after the current value is returned.

System.out.println(index);

… just prints 1.

System.out.println(index++);

… prints 1 then increments index to 2.

System.out.println(index++);

… prints 2 then increments index to 3.

System.out.println(index++);

… prints 3 then increments index to 4.

solved Increment operator java [closed]