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));
}
}
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));
}
}A. 0
B. 1
C. Compilation Error
D. Runtime Error
Answer: Option D
Solution (By Examveda Team)
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.
Join The Discussion
Comments (1)
Related Questions on Constructors and Methods
What is a constructor in Java?
A. A special method to create instances of classes
B. A method used for mathematical calculations
C. A method to perform string manipulations
D. An exception handling mechanism
In Java, which method is automatically called when an object is created?
A. start()
B. main()
C. init()
D. constructor()
What is method overloading in Java?
A. Defining multiple methods with the same name in the same class
B. Calling methods from another class
C. Using methods to load data from a file
D. Running methods in parallel threads

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.