Back to: Java Tutorials
++i are both increment operators, but they work in slightly different ways.
i++ is called the post-increment operator, and it increments the value of
i after it has been used in an expression. For example:
int i = 5; int j = i++; System.out.println(i); // outputs 6 System.out.println(j); // outputs 5
In this example,
i is first assigned the value of 5, and then incremented by 1 using
i++. The value of
i is then used in the assignment to
j, which means that
j is assigned the original value of
i (5) before it was incremented.
++i is called the pre-increment operator, and it increments the value of
i before it is used in an expression. For example:
int i = 5; int j = ++i; System.out.println(i); // outputs 6 System.out.println(j); // outputs 6
In this example,
i is first incremented by 1 using
++i, and then the value of
i is used in the assignment to
j. This means that
j is assigned the new value of
i after it was incremented.
In both cases, the value of
i is incremented by 1. The difference is in when the increment takes place, either before the expression is evaluated (
++i) or after the expression is evaluated (
It’s important to note that the use of
++i can have different effects depending on how it is used in an expression. For example, in a
for loop, the behavior of
++i can be different, which can affect the number of times the loop is executed. It’s always a good idea to understand the behavior of these operators and use them appropriately in your code.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media