What is the Difference Between i++ and ++i in Java?
++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator.
Increment in java is performed in two ways,
1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1.
2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.
int i = 3; int a = i++; // a = 3, i = 4 int b = ++a; // b = 4, a = 4
Post-Increment 0 Pre-Increment 1
Example 2: Cannot apply the increment operator (++) on a constant value
prog.java:8: error: unexpected type int x = ++ 10; ^ required: variable found: value 1 error
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.