Home > Java > javaTutorial > What's the Difference Between Prefix and Postfix Increment/Decrement Operators in Java?

What's the Difference Between Prefix and Postfix Increment/Decrement Operators in Java?

Susan Sarandon
Release: 2024-12-14 10:00:20
Original
167 people have browsed it

What's the Difference Between Prefix and Postfix Increment/Decrement Operators in Java?

Understanding Prefix and Postfix Increment/Decrement Operators in Java

In Java, operators like and -- can be used for incrementing and decrementing variables. However, these operators exhibit different behavior depending on their placement relative to the operand.

Consider the following code:

int i = 3;
i++;
System.out.println(i);    // "4"
++i;
System.out.println(i);    // "5"
System.out.println(++i);  // "6"
System.out.println(i++);  // "6"
System.out.println(i);    // "7"
Copy after login

In this code, the initial value of i is 3.

  • Prefix Increment ( ): In statements like i, the increment operator is placed before the operand. This causes the operand to be incremented first, and then its value is used in the operation. For example, in the third line, i adds 1 to i (which is 5), and then returns 6.
  • Postfix Increment (i ): In statements like i , the increment operator is placed after the operand. This causes the operand to be used in the operation first, and then it gets incremented. For example, in the fourth line, i is used as 6 (its current value), and then incremented to 7.

By understanding the difference between prefix and postfix increment operators, we can control the sequence of operations and achieve desired results.

The above is the detailed content of What's the Difference Between Prefix and Postfix Increment/Decrement Operators in Java?. 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