Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment

Back to Classroom

Identifying the Base Case

Java Basics Course

Engineers From These Top Companies and Universities Trust EXLskills

1M+ Professionals | 100+ Institutions

This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.

-->

Is this course FREE?

Yes, this a 100% free course that you can contribute to on GitHub here!

Let's examine the function of a "base case". It returns a value and does not make any more recurring calls. The values for which the base case stops recurring calls are particular specific inputs. For base cases that are factorial-based, the base case happens when the parameter becomes equal to one. Take a look at the code below.

IdentifyingBaseCaseExample.java

package exlcode;
public class IdentifyingBaseCaseExample {
public static int exampleVariableOne = 10;
public static void main(String[] args) {
System.out.println(factorial(3));
}
public static int factorial(int parameterOne) {
int result;
// base case
// returns 1 when exampleVariableTwo = 1
if (parameterOne == 1) {
return 1;
}
// calls factorial with exampleVariableTwo - 1
// and multiplies the current value of exampleVariableTwo
// with the result of the factorial(exampleVariableTwo - 1)
result = factorial(parameterOne - 1) * parameterOne;
return result;
}
}

Did you receive an output of six? The program is working as intended because three factorial is equal to six. If we take a look at what happens in the method step by step, we see that the if statement is the "base case".

factorial(3)

result = factorial(2) * 3;

factorial(2)

result = factorial(1) * 2;

factorial(1)

return 1;

result = 1 * 2;

return result; (result is 2)

result = 2 * 3;

return result; (result is 6)

Line four and seven, two and nine are referring to the same line of code. This is because the return statement can't be called until factorial(2) and factorial(1) returned a number.