What is the difference between i++ & ++i in a for loop?

user228330 picture user228330 · Feb 23, 2010 · Viewed 319.5k times · Source

I've just started learning Java and now I'm into for loop statements. I don't understand how ++i and i++ works in a for-loop.

How do they work in mathematics operations like addition and subtraction?

Answer

David Johnstone picture David Johnstone · Feb 23, 2010

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4