1Z0-803 · Question #147
Given: public class Painting { private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } public static void main (String[] args) { Painting o
The correct answer is B. null : Fresco. The program initializes two Painting objects, setting one's type field to null and the other's to "Fresco", then prints their values concatenated with a colon.
Question
Given:
public class Painting { private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } public static void main (String[] args) { Painting obj1 = new Painting(); Painting obj2 = new Painting(); obj1.setType(null); obj2.setType("Fresco"); System.out.print(obj1.getType() + " : " + obj2.getType()); } }
Options
- A: Fresco
- Bnull : Fresco
- CFresco : Fresco
- DA NullPointerException is thrown at runtime
How the community answered
(62 responses)- A5% (3)
- B90% (56)
- C2% (1)
- D3% (2)
Why each option
The program initializes two Painting objects, setting one's `type` field to `null` and the other's to "Fresco", then prints their values concatenated with a colon.
This is incorrect because `obj1.getType()` returns `null`, which prints as "null" when concatenated, not an empty string.
B is correct because `obj1.setType(null)` assigns the `null` literal to the `type` field of `obj1`. When `null` is concatenated with a String in Java, it is implicitly converted to the string "null", resulting in "null : Fresco" being printed.
This is incorrect because `obj1`'s type is explicitly set to `null`, not "Fresco".
This is incorrect because assigning `null` to a String reference variable is perfectly valid and does not immediately throw a `NullPointerException`.
Concept tested: Null reference handling, String concatenation
Source: https://docs.oracle.com/javase/tutorial/java/data/strings.html
Topics
Community Discussion
No community discussion yet for this question.