LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 5

Uninitialised elements of an object array Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following Java program?

Main.java
class Item { String name = "item"; }

public class Main {
    public static void main(String[] args) {
        Item[] items = new Item[3];
        items[1] = new Item();
        int nulls = 0;
        for (Item it : items) if (it == null) nulls++;
        System.out.println(nulls + " " + items[1].name + " " + items.length);
        try {
            System.out.println(items[0].name);
        } catch (NullPointerException e) {
            System.out.println("NPE");
        }
    }
}
  • A 2 item 3 NPE Correct
  • B 0 item 3 item
  • C 2 item 1 NPE
  • D 3 item 3 NPE
Correct Answer: Option A

The array holds three references; only one was given an object.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links