LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 20

Counting reachable objects Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What is the output of the following Java program?

Main.java
class N {
    N next;
}

public class Main {
    static int count(N start) {
        int c = 0;
        for (N n = start; n != null; n = n.next) c++;
        return c;
    }

    public static void main(String[] args) {
        N a = new N();
        a.next = new N();
        a.next.next = new N();
        a.next.next.next = new N();
        N b = a.next.next;
        a.next = null;
        System.out.println(count(a) + " " + count(b));
    }
}
  • A 1 2 Correct
  • B 4 2
  • C 1 1
  • D 2 2
Correct Answer: Option A

Cutting a.next leaves only a reachable from a. b still reaches the third and fourth nodes; the second node is now unreachable and can be garbage collected.

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