Reference from the JavaRanch thread ->
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=039606
What is the output of the below program?
public class Increment { public static int getNum(int x) { return x++; } public static void main(String[] args) { System.out.println(getNum(44)); } }
The options for the answers are :
(a) 44 (b) 45 (c) 46
Output:
The answer is :
(a) 44
Reason with Explanation by Henry:
When the getNum() method calculates to value to be returned, it will use the value of x before it gets incremented (post increment means the value of x will be incremented after it has been used).
Sure, the value of x will be incremented, but the value to be returned has already been calculated by then.
Reason with Explanation by me:
Its more or less the same of assignment.
When you have
int x = 2; int y = x++; System.out.println("x = "+x+", y = "+y);
The above SOP will print the value as:
x = 3, y = 2
Why? and How? The value of x is being used in the operation first (ie., assignment). After the appropriate operation (here assignment) is done, the value of x is incremented! Right?
The same holds good in terms of your method as well. The value of x is being used for its operation (here, return value) first and then its incremented. But that does NOT mean that the updated value of x (incremented here) will be reflected back because the updation happens only after the value of x is being used (returned).
Hope this helps!





