Navigator


Archive

201139
201230
201312
20151
201633
201755
201865
201955
20234

Creation date:

Postfix operators

We know that postfix operators(++ and --) are applied after evaluation of expression.

int n = 5;
System.out.println(++n);

will print 6, when

System.out.println(n++);

will print 5 because autoincrement applied after completion of println operation. Now look at the following tricky example and try to predict the result.

class A {
  static int n=5;
  public static void main(String[] args) {
     n=n++;
     System.out.println(n);
  }
}

The common sense (I mean logic) says, that first n = n will set n to 5, then autoincrement will be applied (because of postfix rules) and the value of n will be 6. The result must be the value 6. Now scroll down and look the real output of execution.

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

scroll down

The Java's logic decides that the result must be 5. Now let's try to understand this logic. I think so. First of all the assigning value is prepared, but not yet set to n. Then incrementation is applied to n (the right side of = operator), and finally the prepared before value is set to n. Hence incremented value is overriden by previous value. It's the only thing I can imagine.

Author: Jafar N.Aliyev (Jsoft)

Read also

Static methods can not be overriden

Here I explain, why static methods can not be overriden

Use instanceof carefully

Usage of 'instanceof' method in some situations will give you a compilation error

Java access and nonaccess modifiers

Look at this cheat sheet for Java access and nonaccess modifiers

© Copyright

All articles in this site are written by Jafar N.Aliyev. Reproducing of any article must be followed by the author name and link to the site of origin(this site). This site also keeps the same rules relative to the articles of other authors.