This week's book giveaways are in the iOS and Features new in Java 8 forums. We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line! See this thread and this one for details.
Hello geniuses, gents and ladies! My question is why does it print "inner"? When you add 2 to x on line 8, does that updated variable persist on line 9's if-test? I originally thought that it did not but now I'm wondering. That's the only logic I can imagine to make sense of this cluster...
Marcus Deviln wrote:... When you add 2 to x on line 8, does that updated variable persist on line 9's if-test? I originally thought that it did not but now I'm wondering. ...
No, it doesn't persist. So x+2 > y is true, which passes control to line 9. Then the next condition, y < x is false (x is 7 and y is 9), so the else statement on line 10 gets executed, which then checks !false (not false) which is always true, so line 11 gets executed.
Sometimes nested if statements can get confusing. You might want to expand things with braces so that you better understand how things get executed. If I were to expand the above nested loop structure out as much as possible, using brackets to mark block of code at each nesting level, here is what I would get (I added some comments and an output to denote different conditions...):
Joined: Jan 29, 2009
The contents of the parentheses on line 9 are not a boolean test as you would usually find but an initialization or other words explicitly setting the test to true. If that's the case then that is surely what I missed.
Marcus Deviln wrote:The contents of the parentheses on line 9 are not a boolean test as you would usually find but an initialization or other words explicitly setting the test to true. If that's the case then that is surely what I missed.
Inside the parentheses is a traditional, every day, run of the mill boolean test to see if the value in y is less then the value in x. Nothing special about it. It is not an initialization of any sort, and is not explicitly (or implicitly for that matter) setting anything to true. The key with that line is the semi-colon after the if statement. The ';' signifies an end of statement (and since there are no brackets, the end of the statement also means end of the if() true clause). So the if condition (when true) would run an empty statement (nothing would happen). But that condition is false which means execution falls to the next line.
And since !false is the same thing as true, the statements inside the if() clause gets executed and inner is printed.
";" itself is a complete statement and
when you put it after the if clause in line 9 it does nothing ... i mean nothing other than completing the if clauses statement block ... which otherwise could have been there ...
and since it is false the next to it ... else gets executed ...