nerdexam
Oracle

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

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 void main(String[] args) { Job j1 = new Job("IT", null); DoubleSupplies js1 = j1.getCost(); System.out.println(j1.getName() + ":" + js1.getAsDouble()); } } What is the result?

Options

  • AIT:null
  • BA NullPointerException is thrown at run time.
  • CA compilation error occurs.
  • DIT:0.0

How the community answered

(61 responses)
  • A
    5% (3)
  • B
    70% (43)
  • C
    16% (10)
  • D
    8% (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(), so println is never reached.
  • C (compilation error) is wrong because the code compiles successfully - the null assigned to an Integer field is legal, and the mismatch only manifests at runtime during unboxing. (Note: DoubleSupplies appears to be a typo in this question for double or 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.0 when unboxing null; 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.

Full 1Z0-809 Practice