Can anyone help me to understand this piece of code from OCA/OCP Java SE 8 Programmer Practice Tests CH3Q46.
46. Which of the following is not a possible result of executing the following application?
A. Nothing is printed.
B. The application throws an exception at runtime.
C. Go Outside is printed.
D. Stay Inside is printed.
When I compile and then run from command-line with java OutsideLogic sunny then it outputs "Go Outside".
When I do the same with another argument e.g. java OutsideLogic test then it outputs "Stay Inside".
I do not understand that the third and last operand of && is a ternary operator and outputs a String.
When I flip the ternary operator to the first or second operand of && then it produces an error.
e.g. System.out.print(!false ? "Go Outside" : "Stay Inside" && args!=null && args.equals("sunny")); or
System.out.print(args!=null && args.equals("sunny") && "test"); error: bad operand types for binary operator '&&'
Please help to understand why the third operand of && is not a boolean and (can) outputs a String.
Thanks in advance.
Jeff Stam wrote:I do not understand that the third and last operand of && is a ternary operator and outputs a String.
Well, I would say that statement isn't true, so it's good that you don't understand it. The problem is, what is meant by "the third and last operand of &&"? And I think the key to resolving this is to review the Java order of precedence and see that the ternary operator is lower precedence than almost everything. (Except assignment operators, and you don't have any of those here.) So it isn't that the ternary expression is an operand of && - rather, the && symbols are parts of operands within the ternary expression.
In other words, this:
should be viewed as:
So both the && are part of one big boolean expression, which forms the first operand of the ternary. And "Go Outside" and "Stay Inside" are the second and third operands.
Jeff Stam wrote:. . . The first three operands are a part of the ternary expression.
No, the first three operands are operands of &&. It is only after the &&s have been evaluated that the whole expression (as far as !false) becomes the left operand of the ?: operator.
I presume the correct answr is A.
Little challenge: under what circumstances can the leftmost expression, with != null) evaluate to false.
I'm still trying to solve your challenge and searching for few hours my conclusion is that it is not possible to get args to be null.
If I do not provide any arguments on the command line, then the String array of main() method will be empty but never null.
I hope you will reveal you quiz question so I can learn from this.
Would you please help me so I can solve your challenge.
I am still a beginner and eager to learn but I am stuck.
Every notification on my phone I hope it is an update of this topic but unfortunately so far it isn't.
It is probaly very simple but I cannot connet it to a Java learn objective.