Home > Java > javaTutorial > Java Increment/Decrement Operators: Prefix vs. Postfix – What's the Difference?

Java Increment/Decrement Operators: Prefix vs. Postfix – What's the Difference?

Patricia Arquette
Release: 2025-01-04 07:40:34
Original
490 people have browsed it

Java Increment/Decrement Operators: Prefix vs. Postfix – What's the Difference?

Java: Prefix/Postfix of Increment/Decrement Operators

In Java, increment and decrement operators can be used in two ways: prefix or postfix. The difference between the two lies in the order of evaluation.

Prefix vs. Postfix

Prefix:

In prefix notation, the operator is placed before the variable being modified.

++variable
Copy after login

Postfix:

In postfix notation, the operator is placed after the variable being modified.

variable++
Copy after login

Behavior

The behavior of prefix and postfix operators differs in one key aspect:

  • Prefix: The variable is incremented or decremented before its value is used in an expression.
  • Postfix: The variable is used in an expression before it is incremented or decremented.

Example

Let's consider this code snippet:

int i = 5;
System.out.println(++i); //6
System.out.println(i++); //6 (i = 7, prints 6)
System.out.println(i); //7
Copy after login

Prefix (i to i):

In the first line, i prefixes the increment operator. This means:

  • Increment i by 1 (5 1 = 6).
  • Then, print the result (6).

Therefore, "6" is printed.

Postfix (i to i ):

In the second line, i postfixes the increment operator. This means:

  • Use the current value of i (6) in the expression.
  • Then, increment i by 1 (7).

Therefore, "6" is printed again, but i has been incremented to 7.

The third line simply prints the updated value of i, which is now 7.

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