preincrement / postincrement in java

Variable++ means: Increment variable AFTER evaluating the expression.

++Variable means: Increment variable BEFORE evaluating the expression.

That means, to translate your example to numbers:

System.out.println(i++ + i++);  //1 + 2
System.out.println(++j + ++j);  //2 + 3
System.out.println(k++ + ++k);  //1 + 3
System.out.println(++l + l++);  //2 + 2

Does this clear things up, or do you need further explanations?

To be noted: The value of all those variables after the ‘println’ equal ‘3’.

Since the OP asked, here’s a little ‘use-case’, on where this behaviour is actually useful.

int i = 0;
while(++i < 5) {           //Checks 1 < 5, 2 < 5, 3 < 5, 4 < 5, 5 < 5 -> break. Four runs
    System.out.println(i); //Outputs 1, 2, 3, 4 (not 5) 
}

Compared to:

int i = 0;
while(i++ < 5) {           //Checks 0 < 5, 1 < 5, 2 < 5, 3 < 5, 4 < 5, 5 < 5 -> break. Five runs
    System.out.println(i); //Outputs 1, 2, 3, 4, 5
}

Leave a Comment