How do the post increment (i++) and pre increment (++i) operators work in Java?

Ankit Sachan picture Ankit Sachan · Mar 3, 2010 · Viewed 331.6k times · Source

Can you explain to me the output of this Java code?

int a=5,i;

i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;

System.out.println(a);
System.out.println(i);

The output is 20 in both cases

Answer

Lombo picture Lombo · Mar 3, 2010

++a increments and then uses the variable.
a++ uses and then increments the variable.

If you have

a = 1;

and you do

System.out.println(a++); //You will see 1

//Now a is 2

System.out.println(++a); //You will see 3

codaddict explains your particular snippet.