In c :
int a = 33;
a = a++;
printf("\n\t a :%d",a); // it'll print 34
In Java :
int a = 33;
a = a++;
System.out.printf("\n\t a :%d",a); // it'll print 33
Why the post increment works correctly in C and why not in Java?
In c :
int a = 33;
a = a++;
printf("\n\t a :%d",a); // it'll print 34
In Java :
int a = 33;
a = a++;
System.out.printf("\n\t a :%d",a); // it'll print 33
Why the post increment works correctly in C and why not in Java?
Good question.
There's a difference between a++
and ++a
. In Java (at least), each will increment the variable, but the value represented by the expression is different.
int i = 0;
System.out.println(i++); // 0
int j = 0;
System.out.println(++j); // 1
So you're incrementing a
by 1, but then setting it back to the original value.
From the Java Tutorial:
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.