I just learned that if a return statement contains an increment operation, the return will execute first and the value will be returned before it is incremented. If I increment first in a separate statement, and then return, it works as expected.
private static int incrementIntV1(int a)
{
return a++;
}
private static int incrementIntV2(int a)
{
a++;
return a;
}
public static void main(String[] args)
{
int b = 6;
System.out.println("Increment in return: " + incrementIntV1(b));
System.out.println("Increment first, then return: " + incrementIntV2(b));
System.out.println("Increment with addZero: " + incrementAddZero(b));
}
What is happening with return that makes it sometimes evaluate the whole expression and sometimes not? Is this something special about how the increment operation happens?
If I try:
private static int incrementAddZero(int a)
{
return a++ + addZero();
}
private static int addZero()
{
System.out.print("addZero executes");
return 0;
}
The increment operation still doesn't happen, but I know that the addZero method runs because of the print statement. Why doesn't it increment before the return but it does execute the addZero method before the return?
Hope his makes sense. Thank you much.