Search code examples
javaincrementpost-incrementpre-increment

How many times could a variable be incremented in a single statement?


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.


Solution

  • When you use the assignment operator (=) it is done after the post increment operator. As such you get this:

    int i = 10;
    i = i++;
    System.out.println(i); // print 10
    

    When you are using the post increment twice in the same line, it is not increased after the line is completed, but after the instruction is completed (the instruction being i++). Thus, when doing i = i++ + i++; you are in fact doing this :

    i = i++ + i++; // i=20 Original code
    i = 20 + i++;  // i=21 The first i++ return 20 then increment i to 21
    i = 20 + 21;   // i=22 The second i++ return 21 then increment i to 22
    i = 41;        // i=22 The addition is computed 
    41;            // i=41 and assigne to i
    

    It all as to do with operator precedence.