Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Creating Recursive Methods
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!
In Java, recursion is a programming technique in which a method calls itself to calculate a result. This method is an efficient way to solve problems with only a few lines of code. Take a look at the example of recursion below and figure out what it does.
RecursiveMethodsExample.java
package exlcode;
public class RecursiveMethodsExample {
public static void main(String[] args) {
// prints 1-10 in descending order
print(10);
}
public static void print(int parameterOne) {
if (parameterOne > 0) {
System.out.print(parameterOne + " ");
parameterOne--;
// recursive call
print(parameterOne);
}
}
}
Recursion means that within the course of the method body, there is a statement that calls the same method as the method it belongs in. To prevent a repeating loop from occurring, every recursive method has a "base case" which exits the method when the method is complete.
In the method above, the base case is the if statement because the method will stop when parameterOne is less than 0. Let's track what happens when the method is called.
print(10);
System.out.println(10 + " ");
parameterOne--;
print(9);
System.out.println(9 + " ");
print(8);
and so on until the boolean expression in the if statement evaluates to false.