🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: JVM Memory and Garbage Collection: all 10 questions

Quiz: JVM Memory and Garbage Collection · Question 3 of 10

What does this print? (code)

What does this print?

public class Main {
    static int sum(int n) {
        if (n == 0) return 0;
        return n + sum(n - 1);
    }
    public static void main(String[] args) {
        System.out.println(sum(4));
    }
}
  1. A.4
  2. B.6
  3. C.StackOverflowError
  4. D.10
Answer & explanation

Correct answer: 10

The frames compute 4 + 3 + 2 + 1 + 0 = 10, then pop one by one. The base case stops the recursion.

Can you get the rest right without peeking?

Take the timed Quiz: JVM Memory and Garbage Collection quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →