What is the output of the following application?
1: public class MyClass { 2: public void calculateResult(Integer myFieldA, Integer myFieldB) { 3: boolean process = myFieldA == null || myFieldA.intValue() < 10; 4: boolean value = myFieldA && myFieldB; 5: System.out.print(process || value); 6: } /*from ww w . j a v a 2 s. co m*/ 7: public static void main(String[] unused) { 8: new MyClass().calculateResult(null,203); 9: } 10: }
C.
On line 4, myFieldA
and myFieldB
are numbers, but the && operation can only be applied to boolean expressions.
The code does not compile because of line 4, making C the correct answer.
All of the other lines are correct. Note that if line 4 is fixed, line 3 does not produce a NullPointerException at runtime.
The conditional || and the preceding null check allows the code to only call intValue()
if myFieldA
is not null.