Prefix and Postfix Increment/Decrement Operators in Java
Understanding the difference between prefix and postfix increment/decrement operators is crucial in Java programming. This article explores the effects of these operators in a practical example.
Question:
Consider the following code snippet:
int i = 3; i++; // Postfix increment System.out.println(i); // Prints "4" ++i; // Prefix increment System.out.println(i); // Prints "5" System.out.println(++i); // Prints "6" System.out.println(i++); // Prints "6" System.out.println(i); // Prints "7"
Why does the last call to System.out.println(i) print the value 7?
Answer:
The behavior of this code is governed by the semantics of prefix and postfix increment operators:
Prefix Increment:
int i = 6; System.out.println(++i); // Prints "6"
i evaluates to 7, as it increments i before using its value in the expression. So it prints "6" and increments i to 7.
Postfix Increment:
int i = 6; System.out.println(i++); // Prints "6" (i = 7, prints 6)
i evaluates to 6, as it stores a copy of i, adds 1 to i, and returns the original value. The expression prints "6", but i is now 7.
In the last call, System.out.println(i) prints the current value of i, which is 7. This is because the postfix increment operator had previously updated it to 7.
The above is the detailed content of Java Prefix vs. Postfix Increment/Decrement: Why Does `i ` Result in 7 in This Example?. For more information, please follow other related articles on the PHP Chinese website!