Given the following Calc class:
Which statement is correct? Choose one.
- A. Compilation fails at line 1 only.
- B. Compilation fails at line 2 only.
- C. Compilation fails at line 3 only.
- D. Compilation fails at line 4 only.
- E. Compilation fails at line 5 only.
- F. Compilation fails at more than one line.
- G. All lines compile successfully.
#java #certificationquestion #ocp
Answer: Compilation fails at line 4 only.
First, line 1 would throw a NullPointerException exception as i is initialized by default with null (and doing ++i with i=null fails).
Still, line 1 does compile, so according to the question, we're good with line 1.
Next, lines 2 and 3 same stories as line 1: it throws an NPE but compiles.
Line 4 would fail to compile.
One of the requirements for using the increment and decrement operators is that the target of such an operator must be in storage that can be updated.
Such a value is sometimes referred to as an L-value, meaning an expression that can be on the left side of an assignment.
In line 4, the expression is (i--)-- and the problem is that while i-- is valid in itself, the resulting expression is simply the numeric value that is contained in the object to which i now refers.
And, in the same way, that you cannot write 3++ (where would you store the result?), you cannot increment or decrement such a simple expression.
Line 5 is syntactically valid, the unary plus operator has no effect.
Conclusion: Compilation fails at line 4 only.