Home >Java >javaTutorial >How Do Prefix and Postfix Increment/Decrement Operators Differ in Java?

How Do Prefix and Postfix Increment/Decrement Operators Differ in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 04:45:44345browse

How Do Prefix and Postfix Increment/Decrement Operators Differ in Java?

Understanding Prefix and Postfix Increment/Decrement Operators in Java

Operators like (increment) and -- (decrement) can be applied in a prefix or postfix manner. The placement of these operators affects the evaluation and assignment of the variable.

In the provided Java program:

class PrePostDemo {
    public static void main(String[] args) {
        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
    }
}

The confusion arises in the last two calls to System.out.println.

Prefix Operator:

The prefix increment operator ( ) increments the variable before using it in the operation. So, in System.out.println( i), the value of i is incremented to 6 before being printed.

Postfix Operator:

The postfix increment operator ( ) increments the variable after using it in the operation. So, in System.out.println(i ), the value of i is first printed as 6 (its current value), and then it is incremented to 7.

Example:

The following snippet illustrates the difference:

i = 5;
System.out.println(++i); // 6

This prints "6" because the prefix increment operator increments i to 6 before using it in the println function.

i = 6;
System.out.println(i++); // 6 (i = 7, prints 6)

This also prints "6" because the postfix increment operator prints the current value of i (6), then increments i to 7. The updated value of i (7) is only reflected in subsequent operations.

The above is the detailed content of How Do Prefix and Postfix Increment/Decrement Operators Differ in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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