What will be printed as a result?

public class Test {
    public static void main(String[] s) {
        for (int i = 2; i < 10; i = (i++) + i--, i++) {
            System.out.print(--i);
        }
    }
}
Explanation
In this example, the cycle variable i is changed in three expressions:
1.«System.out.println (--i)» - the variable i is decremented by one. Because the prefix form of the operator is used -, then the new (reduced) value is displayed.
2. «i = (i++) + i--» – the variable i is incremented and then decremented by one, and then the sum is calculates with a value assigned to the same i.
Because the postfix operators form ++/-- is used, at the calculating of the amount the same values are used ​​that were in i before the increase/ decrease. It turns out that this action is equivalent to the following: «i = i + (i + 1)»
3. «i++» – the variable i is incremented by one.

Value of the variable i at each iteration of the cycle:
2 → 1 → 3 → 4
4 → 3 → 7 → 8
8 → 7 → 15 → 16

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes