I'm studying for another attempt at the OCA exam and there was a practice
test question in some uCertify materials that our school provides. They use the Enthuware question banks for these. The question is as follows:
Given the following code:
What is the output?
At first glance, I concluded that it would print True False. After compiling it, I understand the when run it's going to kick out True True. The explanation given only confuses me more. It states:
Notice how the last "else" is associated with the last "if." Now, the first if condition returns true so the next 'if' will be executed. In the second 'if' the condition returns false so the else part will be evaluated which prints 'True True.'
Specifically, the part that says "In the second 'if' the condition returns false...
If the condition returns false, wouldn't the code block for the 2nd 'if' statement run? I think I'm getting it twisted in my head due to a lack of reference variables.
I'm sure this is pretty basic stuff and it's how I'm reading it in my head that needs to be corrected. Would someone be kind enough to walk me through the logic in my brain so I can associate things properly?
1. What's true to begin with?
2. Are if(true) and if(false) assignment statements or something else?
I've refactored this code multiple times and the drunk monkey on my shoulder keeps telling me that in the 2nd 'if' statement whatever is being referenced has to true otherwise the code block for the 2nd 'if' statement would run. It reads allowed in my head as "if something is false, do this. if not, do what is in the else statement. The following code makes perfect sense to me:
When I read this, I can easily see that which code block is going to run in the nested 'if' statement is dependent on the value of x (although, I'm still not sure what's true to begin with). Wow! It feels more like
philosophy than
Java at this point. What's really true man? Two rainbows! What does it all mean?
Your input is much appreciated.