What is recursion in Java?
A
A loop inside a method B
A method that calls itself C
A class that inherits another class D
A static method that returns void
Analysis & Theory
Recursion is when a method calls itself directly or indirectly.
Which of the following is necessary for recursion to work correctly?
A
A loop B
A return statement C
A base condition D
A constructor
Analysis & Theory
A base condition is required to terminate recursion and prevent infinite calls.
What is the output?
```java
public static void test(int n) {
if (n == 0) return;
System.out.print(n + " ");
test(n - 1);
}
test(3);```
A
3 2 1 B
1 2 3 C
3 2 1 0 D
0 1 2 3
Analysis & Theory
It prints the value then calls recursively with `n - 1` until n == 0.
What will happen if the base case is missing in a recursive method?
A
Method returns 0 B
It runs once C
It results in infinite recursion and causes StackOverflowError D
It will return null
Analysis & Theory
Without a base case, the method keeps calling itself until the stack limit is reached.
What is the output?
```java
public static int sum(int n) {
if (n == 1) return 1;
return n + sum(n - 1);
}
System.out.println(sum(3));```
A
6 B
5 C
3 D
1
Analysis & Theory
sum(3) = 3 + 2 + 1 = 6
Which is a classic example of recursion?
A
Bubble Sort B
For Loop C
Factorial calculation D
Array initialization
Analysis & Theory
Factorial is commonly solved using recursion.
What is the base case in the following code?
```java
public static void print(int n) {
if (n <= 0) return;
print(n - 1);
System.out.print(n + " ");
}```
A
print(n - 1) B
System.out.print(n) C
if (n <= 0) return; D
return;
Analysis & Theory
Base case is when `n <= 0`, which stops further recursion.
What is the output?
```java
public static int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
System.out.println(factorial(4));```
A
4 B
10 C
24 D
1
Analysis & Theory
factorial(4) = 4 * 3 * 2 * 1 = 24
Which data structure is primarily used by the JVM to handle recursion?
A
Queue B
Heap C
Stack D
Array
Analysis & Theory
The call stack is used to manage recursive method calls.
What is the output?
```java
public static void fun(int n) {
if (n == 0) return;
fun(n - 1);
System.out.print(n + " ");
}
fun(3);```
A
3 2 1 B
1 2 3 C
3 2 1 0 D
0 1 2 3
Analysis & Theory
This is a post-recursive call; it prints after recursion, resulting in 1 2 3.