ExamVeda
Login
Home
Constructors and Methods
?

What will be the output of the following Java program?
class recursion 
{
    int func (int n) 
    {
        int result;
        result = func (n - 1);
        return result;
    }
} 
class Output 
{
    public static void main(String args[]) 
    {
        recursion obj = new recursion() ;
        System.out.print(obj.func(12));
    }
}

Answer & Solution
Correct Answer: Option D
Let's break down why the answer is a Runtime Error.

The problem lies within the `func` method of the `recursion` class.
It's trying to use recursion, which means a function calling itself.

Here's the critical issue:
The `func` method calls itself (`func(n - 1)`) without a base case.
A base case is a condition that stops the recursive calls.

Without a base case, the function keeps calling itself again and again.

Imagine `func(12)` is called. It then calls `func(11)`, then `func(10)`, and so on.
This continues indefinitely, each call placing another "frame" onto the call stack (memory used to track function calls).

Eventually, the call stack runs out of space. This is called a StackOverflowError.
StackOverflowError is a type of Runtime Error.

Because the error happens while the program is running (not during compilation), it's a runtime error.

Therefore, the correct answer is Option D: Runtime Error.
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Adi Singh
Adi Singh 1 year ago
It will give runtime error because in the method func(n) we didn't provided any base condition for n, which repeats the loop and give the runtime error.