Hi, everyone. I have a question which I dont understand. 1. int i=0; 2. i=i++; 3. System.out.println(i); //print out 0 I thought the result should be 1; as the i in line 2 is assigned to 0, then post ++ increases the i from 0 to 1. However, the program prints out a 0. May anyone explain to me why it turns out like this, please?
here is a bit that i found helpul on that thread - posted by Wasim Ahmed, "They want to know your understanding of Operator pre-increment /post-increment. Here is the easy method that I have learnt and always works. int i = 1 i= i++ + i++ + i answer is 6. How ? put increment operator in inthe parenthesis. i = 1(2) + 2(3) + 3 value of i changes when previous expression performs the increment operation but it doesn't get executed. now drop the values from the parenthesis. i = 1 + 2 + 3 = 6 " I like the idea about using the parenthesis. But i still don't understand how, although ... hold on ... oh okay, i get it ... i think, the post increment indicates that 'i' is equal to 'i' and then it 'would' be equal to the incremented version of 'i' if there is another arithmetic thing going on ... but seeing in the initial example 'i' is printed out in the next line, it does not get incremented?
When using the post-increment/post-decrement operators, the increment/decrement is applied to the value of the variable AFTER the operation is performed. Hence the prefix 'post'. Line 1: variable i is initialized to zero. Line 2: variable i is printed BEFORE the statement finishes execution, so it prints 0, then the value of i is incremented by 1, to 1. Hope this helps some. This type of stuff can be confusing, I know.
Is that a spider in your hair? Here, threaten it with this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss