1

Recently I came across this piece of Java code:

int a=0;
for(int i=0;i<100;i++)
{
    a=a++;
}
System.out.println(a);

The value printed for 'a' is 0. However in case of C, the value for 'a' comes out to be 100.

I am not able to understand why the value is 0 in case of Java.

user2340213
  • 83
  • 1
  • 8

3 Answers3

12
a = a++;

starts with incrementing a, and then reverting a to the old value as a++ returns the not incremented value.

In short it does nothing in Java. If you want to increment, use only the postfix operator like this :

a++;
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Controversial answer already – daniel gratzer May 01 '13 at 17:29
  • Yeah lol, pretty good. –  May 01 '13 at 17:30
  • Dang, the rapid downvotes and upvotes :D – Lews Therin May 01 '13 at 17:30
  • 2
    It's called the [Postfix Increment Operator](http://chortle.ccsu.edu/java5/Notes/chap39/ch39_3.html) – Jason Sperske May 01 '13 at 17:31
  • 2
    First time I've seen an answer go to 7, then 4, then past 7 again. – rgettman May 01 '13 at 17:33
  • I've always read `a = a++` to mean "assign current value of a to a, then increment the resulting value of a so that a is ultimately one higher than before". Why on Earth is it designed so that it means "put aside the old value of a, then increment a, then assign the old value of a back to a so that we end up where we started anyhow". Seems ridiculous that Java runs that way. (I know that you'd never need to use `a = a++` but it still seems a cack-handed way for the JVM to interpret this statement.) – Bobulous May 01 '13 at 17:38
  • If you look at the output of `javap -c` you can see what is going on. `var=var++;` compiles to `iload_1; iinc 1, 1; istore_1` while `var=++var;` compiles to `iinc 1, 1; iload_1; istore_1`; In the first example the value to be assigned is loaded before the increment, so the store operation destroys the effect of incrementing. In the second example the value for the assignment is loaded after the incrementing. `var++;` doesn't load or store because `iinc 1, 1` by itself updates the value in place in the stack. – Jason Sperske May 01 '13 at 18:32
0

a++ is a post increment, so a is assigned the value of a (always 0), and the ghost variable of a is incremented afterwards making no difference to the real a and no result being saved. As a result, a is always assigned to 0, thus the code does nothing

rcbevans
  • 7,101
  • 4
  • 30
  • 46
0

Because:

a = a++;///will assign 'a' to 'a' then increment 'a' in the next step , but from the first step 'a' is '0' and so on

To get 100 you can do Like this:

a = ++a;////here the 'a' will be increment first then will assign this value to a so a will increment in every step 

or

a++;////here the increment is the only operation will do here 
Alya'a Gamal
  • 5,624
  • 19
  • 34