What is the function of the Java operators post increment (i++) and pre increment (++i)?

Overview of Increment Operators

In Java, the increment operator is a shorthand way to increase a variable’s value, usually by 1. They allow shorter notations, hence making the code more readable instead of longer expressions, such as i = i + 1. There are two types of increment operators available in Java, namely post-increment, represented as i++, and pre-increment, represented as ++i.

Incrementation of a variable increases the present value of that variable as a program proceeds with its execution, which is very handy in such situations, like counting, iterating loops, or navigating through data structures. In the case of a loop, for instance, incrementing a variable will help in controlling the number of times the execution of the loop should run, thus making the increment operation an integral part of the control flow mechanism while programming.

Understanding how such operators work can allow developers to write compact and efficient code, especially for performance-critical applications.

Post-Increment (i++)

The post-increment operator-i++ on the other hand increments the value of a variable, but after its current value has been used in an expression. That is to say, it is evaluated with the current value of the variable then that variable gets incremented afterward.

How it Works:

In the case of the post-increment operator, the current value of the variable is used for whatever operation or expression it is part of. Afterwards, its value is increased by 1.

Order of Evaluation:

  • The expression uses the current value of the variable.
  • The variable is incremented by 1 after the expression is evaluated.

Example 1: Simple Post-Increment

int i = 5;
int result = i++;  // result gets the value 5, i is incremented to 6
System.out.println("Result: " + result);  // Output: Result: 5
System.out.println("i: " + i);  // Output: i: 6

In this example:

  • The value of i (which is 5) is assigned to result.
  • After assigning result, the value of i is incremented to 6.

Example 2: Post-Increment in a Loop

for (int i = 0; i < 5; i++) {
    System.out.println("i: " + i);
}

Output:

i: 0
i: 1
i: 2
i: 3
i: 4

Here, the loop uses i++ in the condition:

  • The current value of i is used to print the number.
  • After each iteration, i is incremented by 1.

Example 3: Post-Increment in Method Calls

public static void testMethod(int num) {
    System.out.println("Number: " + num);
}

public static void main(String[] args) {
    int i = 3;
    testMethod(i++);  // Passes 3 to the method, then increments i to 4
    System.out.println("i: " + i);  // Output: i: 4
}

In this example:

  • The method testMethod is called with the current value of i (which is 3).
  • After the method is called, i is incremented to 4.



Pre-Increment (++i)

Prior to being used in an expression, a variable’s value is increased via the pre-increment operator (++i). Thus, the expression uses the updated value of the variable once it has been increased.

How It Operates:

The variable’s value is instantly increased when the pre-increment operator is used, and this new value is applied to all instances of the variable in the expression.

Order of Evaluation:

  • The variable is incremented by 1.
  • The incremented value is used in the expression.

Example 1: Simple Pre-Increment

int i = 5;
int result = ++i;  // i is incremented to 6, result gets the value 6
System.out.println("Result: " + result);  // Output: Result: 6
System.out.println("i: " + i);  // Output: i: 6

In this example:

  • The value of i is incremented to 6 before it is assigned to result.
  • Both result and i have the value 6 after the operation.

Example 2: Pre-Increment in a Loop

for (int i = 0; i < 5; ++i) {
    System.out.println("i: " + i);
}

Output:

i: 0
i: 1
i: 2
i: 3
i: 4

Here, the loop uses ++i in the condition:

  • i is incremented before the condition is checked for the next iteration.
  • However, the output will remain the same as the post-increment example because the loop runs as expected from i = 0 to i = 4.

Example 3: Pre-Increment in Method Calls

public static void testMethod(int num) {
    System.out.println("Number: " + num);
}

public static void main(String[] args) {
    int i = 3;
    testMethod(++i);  // i is incremented to 4, and 4 is passed to the method
    System.out.println("i: " + i);  // Output: i: 4
}

In this instance:

  • Prior to the value of i being supplied to the testMethod, it is increased to 4.
  • As a result, following the method call, I stays at 4 and the method receives the updated value (4).

Example 4: Pre-Increment in an Expression

int i = 2;
int result = 3 * ++i;  // i is incremented to 3, result becomes 9
System.out.println("Result: " + result);  // Output: Result: 9
System.out.println("i: " + i);  // Output: i: 3

In this example:

  • The value of i is incremented from 2 to 3 before the multiplication takes place.
  • Then the new value of i, which is 3, has been multiplied by 3, giving result the value 9.

The Distinctions Between ++i and i++

Although ++i (pre-increment) and i++ (post-increment) both increase a variable’s value by 1, they differ in the order in which they occur within an expression relative to other operations.

Important Variations:

Feature Post-Increment (i++) Pre-Increment (++i)
Evaluation OrderThe current value of i is used first, then it is incremented.i is incremented first, and the new value is used in the expression.
Effect on ExpressionThe original value is used in the expression, and the variable is incremented afterward.The incremented value is used immediately in the expression.
When to UseUseful when you need the current value for the expression before incrementing.Useful when you need the incremented value in the current expression.

Example: Differences in an Expression

Consider the following example where i++ and ++i behave differently within the same expression:

int i = 5;
int result1 = i++ + 2;  // Post-increment
int result2 = ++i + 2;  // Pre-increment

System.out.println("result1: " + result1);  // Output: result1: 7 (i is 6 after increment)
System.out.println("result2: " + result2);  // Output: result2: 9 (i is incremented to 7 before use)
System.out.println("i: " + i);  // Output: i: 7

Explanation:

The first expression (result1 = i++ + 2) explains this.

  • The addition makes use of i’s current value, which is 5.
  • result 1 receives 5 + 2 = 7.
  • After the expression is evaluated, i is incremented to 6.

In the second expression (result2 = ++i + 2):

  • i is first incremented from 6 to 7.
  • The new value of i (which is 7) is used in the addition.
  • result2 gets the value 7 + 2 = 9.

Another Example: Loop Behavior

int i = 0;

// Post-increment in a loop
while (i++ < 3) {
    System.out.println("Post-increment loop: " + i);
}

i = 0;

// Pre-increment in a loop
while (++i < 3) {
    System.out.println("Pre-increment loop: " + i);
}

Output:

arduino
Post-increment loop: 1
Post-increment loop: 2
Post-increment loop: 3

Pre-increment loop: 1
Pre-increment loop: 2

Explanation:

  • In the postincrement Loop, i++, it checks the value before incrementing and this loop will run until i is incremented to 3.
  • In the pre-increment loop (++i), the condition checks the value after incrementing, so the loop stops before reaching 3.

In brief:

  • The post-increment (i++) method increases the variable after using the current value.
  • The pre-increment (++i) method uses the modified value after first incrementing the variable.
  • They produce different results when used in expressions and loops where the order of evaluation makes a difference.

Performance-Related Aspects

In modern Java, there is no noticeable performance difference between the post-increment-i.e., i++-and the pre-increment-i.e., ++i-operators for operating on primitive types such as int, long, float, etc. Both compilers are optimized to similar bytecodes and will hence be running equally fast for normal usage like in loops and simple arithmetic.

 Primitive Types:

In the case of primitive types-like int, for instance-the compiler optimizes both i++ and ++i, and there is no difference for all practical purposes. In any case, where post-increment or pre-increment would be used in either a loop or an expression, the difference between them is irrelevant in modern Java runtime environments.

Special Cases: Non-Primitive Types

While for the primitive types, the difference in performance between i++ and ++i is minimal, with non-primitive types – objects and iterators, for instance-there are some minor considerations.

  • Iterators: When dealing with collections and iterators, especially custom iterators, ++i might be slightly more efficient than i++. This is because post-increment (i++) creates a temporary copy of the iterator’s current state before incrementing it, whereas pre-increment (++i) increments the iterator directly without needing to maintain the original state.

Example:

List<String> list = Arrays.asList("A", "B", "C");
ListIterator<String> iterator = list.listIterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next());  // Pre-increment (++i) might be faster than post-increment (i++)
}

The performance difference is usually negligible, but if you are using custom iterators or are working in performance-critical code, preincrement (++i) can be a bit faster because it avoids the creation of temporary objects.

  • Wrappers of Objects: Similarly, in the case of non-primitive wrappers, such as Integer, Long, or any other custom classes that overload increment operators, preand post-increment may slightly differ in performance, because postincrement operations may imply making extra copies or managing object state.

Conclusion:
In general, between the two methods-i++ versus ++i-modern Java has little difference in terms of performance for primitive types. It should be about readability and clarity. But in some niche cases related to non-primitive types, for instance, iterator or object wrapper, pre-increment (++i) has some slight performance advantages because fewer temporary objects are involved.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.