Java's ++ and -- Operators

The statements i++; and ++i; both increase the value of i by 1.
The statements i--; and --i; both decrease the value of i by 1.

Therefore both i++; and ++i; are equivalent to i = i + 1;
and both i--; and --i; are equivalent to i = i - 1;

However there is a difference:
x = a[++i]; is equivalent to i = i + 1; x = a[i];
x = a[i++];
is equivalent to x = a[i]; i = i + 1;

If instead of incrementing the index of an array, we increment the contents of one of its elements, then both a[i]++; and ++a[i] are equivalent to a[i] = a[i] + 1; and a[i]--; and --a[i] are equivalent to a[i] = a[i] - 1;

However, if i is obtained from a method m( ) which returns a different value each time it is called as in a[m(i)]++; , then a[m(i)]++; is not equivalent to a[m(i)] = a[m(i)] + 1; and a[m(i)]--; is not equivalent to a[m(i)] = a[m(i)] - 1;

The statement a[m(i)]++; increments a particular element of a[] while the statement a[m(i)] = a[m(i)] + 1; sets the value of one element of a[] to one more than the value of some other element of a[].

Illustration of the effects of ++i and i++:

class IncOrder {
  public static void main( String[] args ) {
    int i = 16;
    System.out.print(++i + " " + i++ + " " + i);
  }
}
Output is 17 17 18.
This page's parent within this Web Site. About this Web Site. Its home page. Email its Author.