Consider the following code segment. Which of the following best describes what happens?
Building b = null;
System.out.println(b.label());
null.NullPointerException when the method is called.Building object automatically.null reference refers to no object, so calling label through it throws a NullPointerException at run time.
Explanation
A reference variable that stores null does not refer to any object. The code compiles, but at run time there is no object for the method to run on, so the program stops with a NullPointerException.
- A is not correct: printing happens only if the call succeeds, and the receiver refers to no object, so the program stops before any value reaches the output.
- B is not correct: the method never runs, so no text of any kind is produced; the failure occurs at the moment the call is made.
- D is not correct:
newis what builds an object, and this segment never uses it, so anullreference is not replaced automatically.