nerdexam
Oracle

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.

Working with Methods and Encapsulation

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)
  • A
    5% (3)
  • B
    88% (58)
  • C
    6% (4)
  • D
    2% (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.

A: Fresco

This output implies `obj1.getType()` returned an empty string, which is not how a null String behaves during concatenation.

Bnull : FrescoCorrect

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.

CFresco : Fresco

This output suggests that both objects had their `type` set to 'Fresco', which is incorrect as `obj1`'s type was explicitly set to null.

DA NullPointerException is thrown at runtime

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

#getters#setters#null values#String

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice