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
Release: 2024-12-19 04:45:44
Original
336 people have browsed it

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

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

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

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!

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