public class Arg{ public static void main(String argv[]){ Arg inc = new Arg(); int i =0; i = i++; System.out.println(i); //line 1, 0???
int k =0; System.out.println(k++); //0 System.out.println(k); //line3, 1 } } //hi, my confusion is why the line 1 still give 0? //after i= i++, the i should be 1 now even if it is post increment. //it should like the same in the line 3. Someone please explain to me, thanks!
Michael Lin, int i =0; // line 1 i = i++; // line 2
There are 3 steps involved in this : 1. First in line2 i is assigned 0 (cos of line 1, and i++ is a postincrement operator) 2. Then i++ is evaluated ( so i = 1) 3. Now i = 0 is evaluated ( from step 1) Hope this clears rajani
Hi micheal, I have he same doubt that how the assignment is happening. I tried this which is the equivalent of your code. public class StrangeAssignment { public static void main(String a[]) { int i = 0; i = i = i+1; // i++ is equivalent to i=i+1. System.out.println(i); } } But the answer is 1 !!. Really it is a strange assignment. I tried the same in C/C++ it's giving 1. Regards, vadiraj
ok lets take this expression i = i++ + i what is the answer .. its one.. what it did was it writes the value of i before the + sign ( i=0) which is zero till now and then increments the value of i by 1 our expresion becoms i = 0 +... and i becomes 1 so now the value of i after + sign is assigned 1( as now i = 1) so the final expression becomes ( till now i is one) i = 0 + 1 now calculation the expression we get i = 1 if u got this now we will go back to ur question now our expression is i = i++ first i=0 so after the = sign i is assigned 0 and the value of i is incremented by 1 and i becomes 1 and our expression becomes i = 0 ( till now the value of i is one) but after evaluating this expression i becomes 0 HTH anil
Does this mean that the following statements public class Postincrement{ public static void main(String args[]){ i=0; i=i++ + i++; System.out.println(i) ; } } would print 0 but the value of the variable i is 2 ? Thanks Sudhir
I think confusion is due to behaviour of operator in C. In C it will do i= 0; i=i++;/* 2 */ printf("%d",i); ans i =1 C do it as assign i=0 on line two then increment it by 1. Java seems workingin different way
Post by:autobot
This is awkward. I've grown a second evil head. I'm going to need a machete and a tiny ad ...
a bit of art, as a gift, the permaculture playing cards