LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 12

Changing objects through a list Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.List;

class Task {
    String title;
    boolean done;
    Task(String t) { title = t; }
}

public class Main {
    public static void main(String[] args) {
        Task t = new Task("Write code");
        List<Task> list = new ArrayList<>();
        list.add(t);
        list.add(t);                        // the same object added twice
        list.add(new Task("Test"));
        list.get(0).done = true;
        long done = list.stream().filter(x -> x.done).count();
        System.out.println(list.size() + " " + done + " " + t.done);
    }
}
  • A 3 2 true Correct
  • B 3 1 true
  • C 2 1 true
  • D 3 2 false
Correct Answer: Option A

The list stores references; positions 0 and 1 refer to the same Task, so marking one marks "both".

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