LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 3

A getter returning an unmodifiable view Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.Collections;
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 Collections.unmodifiableList(members); }
}

public class Main {
    public static void main(String[] args) {
        Group g = new Group();
        g.join("Asha");
        List<String> view = g.getMembers();
        g.join("Ravi");
        String r;
        try { view.add("John"); r = "added"; } catch (UnsupportedOperationException e) { r = "refused"; }
        System.out.println(view + " " + r);
    }
}
  • A [Asha, Ravi] refused Correct
  • B [Asha] refused
  • C [Asha, Ravi, John] added
  • D [Asha] added
Correct Answer: Option A

The view shows Ravi (added later through join) but rejects direct changes.

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