1Z0-803 · Question #228
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 ob
The correct answer is B. null : Fresco. The code illustrates the handling of null String references in Java, including valid assignment of null and its conversion to the string 'null' during concatenation.
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()); } } What is the result?
Options
- A: Fresco
- Bnull : Fresco
- CFresco : Fresco
- DA NullPointerException is thrown at runtime
How the community answered
(66 responses)- A5% (3)
- B88% (58)
- C6% (4)
- D2% (1)
Why each option
The code illustrates the handling of null String references in Java, including valid assignment of null and its conversion to the string 'null' during concatenation.
This output implies `obj1.getType()` returned an empty string, which is not how a null String behaves during concatenation.
In Java, an uninitialized String field is null by default, and `setType(null)` explicitly sets `obj1.type` to null. When `obj1.getType()` returns null and is concatenated with other strings, Java implicitly converts the `null` reference into the literal string 'null' for display.
This output suggests that both objects had their `type` set to 'Fresco', which is incorrect as `obj1`'s type was explicitly set to null.
A `NullPointerException` is not thrown because operations like assigning null, returning null, or concatenating null with a string are valid and handled gracefully by Java.
Concept tested: Null references, String concatenation with null
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Topics
Community Discussion
No community discussion yet for this question.