Difference Between i++ and ++i Operators in Java

This tutorial introduces differences between the pre-increment, ++i
, and post-increment, i++
, operators in Java.
In Java, the ++i
and i++
operators are known as increment operators. The ++i
is known as the pre-increment operator, while the i++
operator is known as the post-increment operator. As the name implies, the post-increment operator increments the variable after being used, and the pre-increment operator increments the variable before being used. These are unary operators too.
There are several ways to use these operators, such as in the loop for increment the loop conditional variable, iterate all the elements of a List
in Java. For example, the for
loop, the for-each
loop, the forEach()
method with list or stream, etc. Let’s see some examples.
Pre-Increment (++i
) Operator in Java
The increment operators are mostly used in a loop to automate the loop iterations. In this example, we use the pre-increment operator to increment the variable by 1 in each iteration of the loop. This is a simple example, and it does not explain the proper difference of both increment operators, but we can get the idea of how we can use this in the loop. See the example below.
public class SimpleTesting{
public static void main(String[] args) {
int[] arr = {2, 5, 6, 9, 4};
for (int i = 0; i < arr.length; ++i)
{
System.out.print(arr[i]+" ");
}
}
}
Output:
2 5 6 9 4
Pre-Increment (++i
) vs Post-Increment (i++
) Operator in Java
In this example, we can clearly see the difference between pre-increment and post-increment operators. We use a variable a
and applied post-increment to it and see it prints the same value it holds because it increments after being used once. And we create a variable b
that prints the incremented value because it increments before being used. See the example below.
public class SimpleTesting{
public static void main(String[] args) {
int a = 1;
System.out.println(a++);
int b = 1;
System.out.println(++b);
}
}
Output:
1
2
Related Article - Java Operator
- Diamond Operator in Java
- Unsigned and Signed Right Bit Shift Operator in Java
- Java Bitwise Operators
- Remainder Operator in Java
- Logical Operators and Short Circuit in Java
- Operator Overloading in Java