This week's book giveaway is in the JDBC forum. We're giving away four copies of SQL Antipatterns: Avoiding the Pitfalls of Database Programming and have Bill Karwin on-line! See this thread for details.
Book says, "The first expression compares x and y and the result is false, because increment on x doesn't happen until after the == test is made"
OK. It is sensible.
But how about code at below.
public class Increment { public static int getNum(int x) { return x++; } public static void main(String[] args) { System.out.println(getNum(44)); } }
Please explain why the output is 44 instead of 45. Any help will be appreciated.
Thanks, Mehmet
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 11293
posted
But how about code at below.
Please explain why the output is 44 instead of 45. Any help will be appreciated.
Can you please explain why it should be 45 instead of 44?
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.
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).