Java Interview Prep: Post-increment(i++) and Pre-increment operators (++i)


In Java, the post-increment and pre-increment operators (++) are used to increase the value of a variable by 1, but they behave slightly differently in terms of when the increment occurs relative to their use in expressions. Here’s a breakdown of both:

1. Post-Increment (i++)

  • Operation: First, the current value of the variable is used in the expression, and then it is incremented by 1.

  • Syntax: i++

  • Behavior:

    • First, the current value of i is returned (used in an expression, for example).
    • Then, i is incremented.
  • Example:

    int i = 5;
    int j = i++; // j = 5, i = 6
  • In the example above, i is used as 5 in the assignment to j, and then i is incremented to 6. The increment happens after the value of i is assigned to j.

2. Pre-Increment (++i)

  • Operation: First, the value of the variable is incremented by 1, and then the new value is used in the expression.

  • Syntax: ++i

  • Behavior:

    • First, i is incremented.
    • Then, the updated value of i is returned (used in the expression).
  • Example:

    int i = 5;
    int j = ++i; // j = 6, i = 6
  • In this case, i is first incremented to 6, and then that updated value is assigned to j.

Key Differences:

  • Post-Increment (i++):
    • Returns the value before incrementing.
    • The increment happens after the value is used in the expression.
  • Pre-Increment (++i):
    • Returns the value after incrementing.
    • The increment happens before the value is used in the expression.

Examples:

public class IncrementExample {
    public static void main(String[] args) {
        int x = 5;
        int y = x++;  // Post-increment: y = 5, x becomes 6
        System.out.println("Post-increment: x = " + x + ", y = " + y);
        
        x = 5;
        y = ++x;  // Pre-increment: y = 6, x becomes 6
        System.out.println("Pre-increment: x = " + x + ", y = " + y);
    }
}

Output:

Post-increment: x = 6, y = 5
Pre-increment: x = 6, y = 6

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example