| Author |
Increment Operator question
|
Mehmet Gursul
Greenhorn
Joined: Jan 26, 2006
Posts: 6
|
|
Hi everybody, K&B book page 291; int x=2; int y=3; if (y==x++ | x<++y) ... 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: 13399
|
|
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. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3287
|
|
Its more or less the same of assignment. When you have The above SOP will print the value as: 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). HtH. [ July 09, 2007: Message edited by: Raghavan Muthu ]
|
Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
|
 |
Mehmet Gursul
Greenhorn
Joined: Jan 26, 2006
Posts: 6
|
|
Thanks, Henry and Raghavan. "The value of x is being used for its operation (here, return value)" is a good explanation. Thanks again..
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3287
|
|
Welcome Mehmet Gursul Its our pleasure!
|
 |
 |
|
|
subject: Increment Operator question
|
|
|