Main Content

Incrementing a variable in Java - Pre and Post Increment

Archive - Originally posted on "The Horse's Mouth" - 2014-12-08 23:16:06 - Graham Ellis

Java (and C, Perl and PHP) supports the ++ operator to increment a variable - in other word, do add 1 to the value it holds and save the reult back in the same place.

You can write
  counter++;
or
  ++counter;
and as statemnets on their own, they'll do the same thing.

However, embed them with another statement and it does make a differene.
  another = summat++;
is different to
  another = ++summat;

Both of these increment the variable summat, but what get stored into another will differ.
• With ++ after the variable name, the extra 1 is added after the other uses of that variable in the line - in other words, another gets set to the original value of summat
• With ++ before the variable name, the extra 1 is added before the other uses of that variable in the line - in other words, another gets set to the new value of summat

With the ++ in front, it's know as pre-increment - increment before other use
With the ++ behind, it's know as post-increment - increment after other use

Sample of that it use - [here] from the current Java course