nerdexam
Oracle

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.

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()); } }

Options

  • A: Fresco
  • Bnull : Fresco
  • CFresco : Fresco
  • DA NullPointerException is thrown at runtime

How the community answered

(62 responses)
  • A
    5% (3)
  • B
    90% (56)
  • C
    2% (1)
  • D
    3% (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.

A: Fresco

This is incorrect because `obj1.getType()` returns `null`, which prints as "null" when concatenated, not an empty string.

Bnull : FrescoCorrect

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.

CFresco : Fresco

This is incorrect because `obj1`'s type is explicitly set to `null`, not "Fresco".

DA NullPointerException is thrown at runtime

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

#null reference#String concatenation#getter/setter methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice