1Z0-809 · Question #190
public class Job { String name; Integer cost; Job(String name, Integer cost) { this.name = name; this.cost = cost; } String getName() { return name; } int getCost() { return cost; } public static…
The correct answer is B. A NullPointerException is thrown at run time. Option B is correct because getCost() declares a return type of int (a primitive), but cost is stored as a nullable Integer wrapper. When cost is null, the statement return cost; attempts to auto-unbox the null Integer into a primitive int, which throws a NullPointerException…
Question
Options
- AIT:null
- BA NullPointerException is thrown at run time.
- CA compilation error occurs.
- DIT:0.0
How the community answered
(61 responses)- A5% (3)
- B70% (43)
- C16% (10)
- D8% (5)
Explanation
Option B is correct because getCost() declares a return type of int (a primitive), but cost is stored as a nullable Integer wrapper. When cost is null, the statement return cost; attempts to auto-unbox the null Integer into a primitive int, which throws a NullPointerException at runtime - before main ever reaches the println call.
Why the distractors are wrong:
- A (IT:null) is wrong because Java cannot auto-unbox a null wrapper type silently; the NPE fires during
getCost(), soprintlnis never reached. - C (compilation error) is wrong because the code compiles successfully - the
nullassigned to anIntegerfield is legal, and the mismatch only manifests at runtime during unboxing. (Note:DoubleSuppliesappears to be a typo in this question fordoubleor similar; if taken literally it would cause a compile error, but the intended lesson is about unboxing.) - D (IT:0.0) is wrong because Java does not substitute a default value like
0.0when unboxingnull; it always throws NPE.
Memory tip: Whenever a primitive return type (int, double, boolean) is backed by a nullable wrapper field (Integer, Double, Boolean), treat it as a hidden NPE trap - the unboxing happens invisibly on the return line, not at the call site.
Community Discussion
No community discussion yet for this question.