IF x > y THEN return x
once you return then no further statements in the method are executed. On the other hand, if x is NOT > y then the return x is NOT execute and so processing continues on to the next statement which is return y.
The return statement exits the method. So, let's see what we got here:
Note: even though the if statement has just one line of code, I inserted the braces to make the code more easy to read.
The if statement just tests if the x value is greater than y. There is no test for equal values.
And remember that we can omit the braces when the if statement's block of code has just one line of code, like this:
Urs Waefler wrote:This is the code: It returns the higher value. To me it seems that there is an else missing. I do not understand why it does not always return y.
One thing is I would recommend is to only have a single return exit point, not two. While it may not seem like a big deal in such a small piece of code, if you get into the habit you may have a long method with lots of those exit points making debugging very difficult.
The reason your code is always returning the larger of the two numbers is your algorithm.
If you pass 1, and 2
1 is not greater than 2, so your code returns 2 from the bottom return statement.
If you pass 2 and 1
2 is greater than 1 so you return 2 from the initial return statement.
Thus, the way you wrote your IF statement, you're guaranteed to always get the larger of the two numbers (like a Math.max()).
Creating a single return int variable, having a single return point, and debugging your code will show you exactly what's going on - though you can still debug (step through) your code as is and see what's happening.