LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 13

A counter that cannot be reset from outside Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following Java program?

Main.java
class PageViews {
    private long views;
    private long uniqueVisitors;
    private final java.util.Set<String> seen = new java.util.HashSet<>();

    void visit(String visitorId) {
        views++;
        if (seen.add(visitorId)) uniqueVisitors++;
    }

    long views() { return views; }
    long unique() { return uniqueVisitors; }
}

public class Main {
    public static void main(String[] args) {
        PageViews pv = new PageViews();
        for (String v : "a b a c b a d".split(" ")) pv.visit(v);
        System.out.println(pv.views() + " " + pv.unique());
    }
}
  • A 7 4 Correct
  • B 7 7
  • C 4 4
  • D 7 3
Correct Answer: Option A

Visitors a, b, c and d are unique; nothing outside can tamper with either counter.

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