Question 2
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
class Group {
private final List<String> members = new ArrayList<>();
public void join(String n) { if (members.size() < 2) members.add(n); }
public List<String> getMembers() { return members; }
}
public class Main {
public static void main(String[] args) {
Group g = new Group();
g.join("Asha"); g.join("Ravi"); g.join("Meena");
g.getMembers().add("John");
g.getMembers().add("Zoya");
System.out.println(g.getMembers().size() + " " + g.getMembers());
}
}
- A 4 [Asha, Ravi, John, Zoya] Correct
- B 2 [Asha, Ravi]
- C 3 [Asha, Ravi, Meena]
- D 5 [Asha, Ravi, Meena, John, Zoya]
Correct Answer: Option A
join enforces the limit of 2, but the getter hands out the real list, so callers bypass it.
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!