The Increment and Decrement Operators

++ and -- are operators that add and subtract one from their operands.

Java provides two unary operators that can be used to increment and decrement numeric values by 1: the pre-increment (++i) and pre-decrement (--i) operators, and the post-increment (i++) and post-decrement (i--) operators.

The pre-increment and pre-decrement operators increment or decrement the value of the variable before it is used in an expression. Here is an example of pre-increment:

int i = 0; int j = ++i; System.out.println("i = " + i); // Output: i = 1 System.out.println("j = " + j); // Output: j = 1

In this example, the value of i is incremented by 1 before it is assigned to j. The output shows that both i and j have a value of 1 after the code is executed.

The post-increment and post-decrement operators increment or decrement the variable's value after it is used in an expression. Here is an example of post-increment:

int i = 0; int j = i++; System.out.println("i = " + i); // Output: i = 1 System.out.println("j = " + j); // Output: j = 0

In this example, the value of i is assigned to j before it is incremented by 1. The output shows that i has a value of 1, and j has a value of 0 after the code is executed.

Both the pre-increment and post-increment operators can be used to simplify code and improve readability by avoiding the need to write separate lines of code to increment or decrement a variable. However, it's important to use these operators with care to avoid unintended behavior or confusion in the code.

 

 

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark