Question 5
Back to Exercise
What is the output of the following Java program?
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!