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
iis returned (used in an expression, for example). - Then,
iis incremented.
- First, the current value of
Example:
In the example above,
iis used as 5 in the assignment toj, and theniis incremented to 6. The increment happens after the value ofiis assigned toj.
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:
++iBehavior:
- First,
iis incremented. - Then, the updated value of
iis returned (used in the expression).
- First,
Example:
In this case,
iis first incremented to 6, and then that updated value is assigned toj.
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:
Output:
Comments
Post a Comment