I am currently reading Barry Burd's Java For Dummies, and came upon this little exercise.
The exercise is regarding post and pre-increment. In the problem (please see the code) I was able to figure out the answers to all the lines(without the help of compiler) except for the last one. Which does not make sense according to my knowledge of post/pre-increment so far.
Please advise on how or why the result is not what I expected.
I tried initializing and declaring a new variable (int) with the value of "20" and then did "i = i++ + i++", but still received the same result (41).
Also tried doing out.println(i) twice, but it still printed 41.
import static java.lang.System.out;
public class Main
{
public static void main(String[] args) {
int i = 10;
out.println(i++); //10(post11)
out.println(--i); //10(pre11-1)
--i; //9(pre10-1)
i--; //9(post8)
out.println(i); //8
out.println(++i); //9(pre8+1)
out.println(i--); //9(post8)
out.println(i); //8
i++; //8(post9)
i = i++ + ++i; //i = 9(post10) + 10(pre9+1) = 19(post20)
out.println(i); //20
i = i++ + i++; //i = 20(post21) + 20(post21) = 40(post42)
out.println(i); //41 (result copied from compiler)
}
}
I expected the last line to print 42 rather than 41, since "20" gets added twice, and also gets incremented twice.