Home > Java > javaTutorial > Java Prefix vs. Postfix Increment/Decrement: Why Does `i ` Result in 7 in This Example?

Java Prefix vs. Postfix Increment/Decrement: Why Does `i ` Result in 7 in This Example?

Patricia Arquette
Release: 2024-12-17 02:41:24
Original
280 people have browsed it

Java Prefix vs. Postfix Increment/Decrement: Why Does `i  ` Result in 7 in This Example?

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"
Copy after login

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 ( ): Increments the operand before it is used in an expression.
  • Postfix increment ( ): Increments the operand after it has been used in an expression.

Prefix Increment:

int i = 6;
System.out.println(++i); // Prints "6"
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template