How do the post increment (i++) and pre increment (++i) operators work in Java?
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a
increments the value and immediately returns it.
a++
also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
When to use post increment and pre increment in Java
PRE-increment is used when you want to use the incremented value of the variable in that expression., whereas POST-increment uses the original value before incrementing it.
Whenever your code encounters a PRE-increment, it increments the value of that variable in the memory, then load that value and continues reading the expression.
POST-increment does the opposite, it loads that value of that variable in the memory, then increments the value and continues reading the expression.
To make it more clear, consider this
int i = counter++;
is equivalent to
int i = counter;
counter = counter + 1;
WHEREAS
int i = ++counter;
is equivalent to
counter = counter + 1;
int i = counter;
EDIT: My StackOverflow comments arent working, so I'll just edit it here.
What I'm saying it, it only matters when you use that value in an expression.
sum = 0
counter = 0;
sum = (++counter)+(++counter)+(counter++)
evaluates as
sum = 0
counter = 0
//For first ++counter
counter = counter + 1
sum = counter
//For second ++counter
counter = counter + 1
sum = sum + counter
//For first counter++
sum = sum + counter
counter = counter + 1
Result of function that includes pre- and post-increment differs
i++ * ++i * 2
--> 1 * 3 * 2 --> 6++x * x++ * 2
--> 2 * 2 * 2 --> 8
Important values in bold.
The difference between the prefix and postfix increment when returning values in Java can be better summarized by Oracle themselves (my bold again for highlighting purposes):
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
Source here.
In your specific case, as the postfix evaluates to the original value and the order of operations is left to right for same arithmetic operator - here, only multiplier applies - your operations are translated as above.
In Java, how does a post increment operator act in a return statement?
The key part is that a post increment/decrement happens immediately after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated. For instance, suppose you wrote:
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++ + giveMeZero();
}
public int giveMeZero()
{
System.out.println(_ix);
return 0;
}
}
That would print out the incremented result as well, because the increment happens before giveMeZero()
is called.
post-increment, pre-increment. JAVA
EDITED
Here are the steps to evaluate the expression:
- Evaluate all the expression that has increment/decrement from left to right
- Replace all variable with their true value
- Evaluate the expression using PEMDAS rule
Example:
int x = 4;
int y = ++x * 5 / x-- + --x;
first we need to substitute all values of
x
before evaluating the expression (substitute from left to right)++x
-> since it is a post increment we will first incrementx
before substituting, thusx
will be 55 * 5 / x-- + --x
-> this will be the new equation
now we will substitutex
inx--
x--
-> since it is a post decrementx
here will be substituted with 5 and after the substitution decrementx
, thusx
will be 45 * 5 / 5 + --x
-> this will be the new equation
now we will substitutex
in--x
--x
-> since it is a pre decrement we will first decrementx
substituting, thusx
will be 35 * 5 / 5 + 3
// this will be the new equationSince there are no variables in the equation we will now evaluate the expression using PEMDAS
25 / 5 + 3
5 + 3
8
thus the result will be 8
Related Topics
How to Count the Number of Documents Under a Collection in Firestore
Failed to Resolve Com.Google.Android.Gms Play-Services-Auth:11.4.0
Parsing Query Strings on Android
Must Override a Superclass Method' Errors After Importing a Project into Eclipse
Execution Failed For Task :App:Compiledebugjavawithjavac in Android Studio
Set Imageview Width and Height Programmatically
Difference Between Jsonobject and Jsonarray
How to Ping External Ip from Java Android
Error: Could Not Find or Load Main Class
Running Jmap Getting Unable to Open Socket File
How to Execute Bash Command With Sudo Privileges in Java
Growing Resident Memory Usage (Rss) of Java Process
React on Global Hotkey in a Java Program on Windows/Linux/Mac
Gradle Finds Wrong Java_Home Even Though It's Correctly Set
How to Stop Repeated Keypressed()/Keyreleased() Events in Swing
Efficiency of Java "Double Brace Initialization"
Error Java.Lang.Outofmemoryerror: Gc Overhead Limit Exceeded