Hello everybody,
It’s Michael, and today’s Java lesson will be on recursion.
What is recursion? In the context of Java programming, recursion is whenever a program has a subtask that’s a smaller version of the entire program’s task. To keep things simple, I will mostly talk about recursion as it relates to recursive methods, which are methods that call themselves.
You might be thinking “How can a method call itself?” The answer would be with a recursive call, which is a method’s prompt to call itself.
Now let’s demonstrate recursive methods with a simple example:
package javalesson13;
public class JavaLesson13
{public static void main(String[] args)
{
increasedouble(19);
}public static void increasedouble (int num)
{
if (num >= 200)
{
System.out.println();
}else
{
System.out.println(num);
increasedouble(num * 2);
}
}}
And here’s the output:
run:
19
38
76
152BUILD SUCCESSFUL (total time: 0 seconds)
This program is a rather simple example of recursion; in this example, I pass a number into the increasedouble method. The number will keep doubling so long as each successive result is less than 200. Once the closest possible number to 200 is reached, the program will run the System.out.println() command and then stop running. The line (if num >= 200)-if the number obtained is greater than or equal to 200-functions as a base case, which is the condition that needs to be reached to stop recursion.
- I know
increasedoubleisn’t the best possible method name, but I couldn’t usedoubleas a method name because that is a reserved word, which are words that can’t be used in variable, object, class, or method names since they are already part of Java syntax (sorry I didn’t mention this earlier)
OK, so you might be thinking that this program could have been written with a simple while or do-while loop. Writing this program with a loop would certainly work, and would be the preferred way of solving this particular programming problem. However, I wanted to demonstrate recursion by starting off with a simple example; plus, there are cases where recursion will work better than loops.
Here’s a more complex example of recursion:
public class JavaLesson13
{public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println(“Please pick a number: “);
int num = s.nextInt();
System.out.println(“The month is ” + returnMonth(num));
}public static String returnMonth (int num2)
{
String month = null;switch(num2)
{
case 1: month = “January”; break;
case 2: month = “February”; break;
case 3: month = “March”; break;
case 4: month = “April”; break;
case 5: month = “May”; break;
case 6: month = “June”; break;
case 7: month = “July”; break;
case 8: month = “August”; break;
case 9: month = “September”; break;
case 10: month = “October”; break;
case 11: month = “November”; break;
case 12: month = “December”; break;default:
{
System.out.println(“ERROR”);
System.exit(0);
}}
return month;
}
}
And here’s some sample output:
run:
Please pick a number:
11
The month is November
BUILD SUCCESSFUL (total time: 6 seconds)
In this program, the user inputs a number and the message The month is along with the corresponding month for that number will be displayed–IF the number entered is between 1 and 12. I return the correct month by calling the returnMonth
Here’s where I introduce two new Java terms-switch and case. Switch statements have similar logic to if-else statements, but unlike if-else statements, switch statements allow for multiple scenarios.
- OK,
ifstatements with multiple instances ofelse ifcan handle multiple scenarios as well. However, having aswitchstatement with multiple instances ofcasemakesif-else if-elsestatements unnecessary. Plusswitchstatements are easier to read and understand-but that’s just my opinion.
As you can see in the example above, switch statements have several instances of case. Case statements detail all possible scenarios for a program along with a default case (using the reserved word default). The code in the default case will run if none of the other cases are true.
In this case, the default case will run if the number inputted isn’t between 1 and 12. All that will happen in the default case is that the word ERROR will be displayed and the program will stop running (as denoted by the System.exit(0) line). However, if the number inputted is between 1 and 12, then one of the twelve case statements will be executed depending on the user’s input.
- Think of the
defaultstatement as theelsein anif-else if-elsecode block, since theelsestatement will execute if neither theifnor theelse ifstatements are true, just as thedefaultstatement will execute if none of the othercasestatements are true.
Notice how all of the case statements (not including the default statement) end with break. This is because break will end the program once the correct case is found and the correct output is returned. Plus, if I didn’t have any break statements, the program could possibly run infinitely (though this is just my theory).
Now here’s a sample output that will run the default case:
run:
Please pick a number:
22
ERROR
BUILD SUCCESSFUL (total time: 6 seconds)
One more thing I wanted to note about recursion is that, even though the above example used numbers as cases, you can use other data types for cases as well (such as booleans and Strings).
Here’s an example of using Strings in case statements, which simply does the opposite of the previous example program (ask for the month and print the corresponding number):
package javalesson13;
import java.util.Scanner;public class JavaLesson13
{public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println(“Please pick a month: “);
String month = s.nextLine();
System.out.println(“The number is ” + returnNumber(month));
}public static int returnNumber (String month)
{
int num = 0;switch(month)
{
case “January”: num = 1; break;
case “February”: num = 2; break;
case “March”: num = 3; break;
case “April”: num = 4; break;
case “May”: num = 5; break;
case “June”: num = 6; break;
case “July”: num = 7; break;
case “August”: num = 8; break;
case “September”: num = 9; break;
case “October”: num = 10; break;
case “November”: num = 11; break;
case “December”: num = 12; break;default:
{
System.out.println(“ERROR”);
System.exit(0);
}}
return num;
}
}
And here’s some sample output using the current month-November:
run:
Please pick a month:
November
The number is 11
BUILD SUCCESSFUL (total time: 2 seconds)
Here are the tweaks I made to the previous program:
- Swapped the return and parameter types of the
returnMonthmethod-in the previous example, thereturnMonthmethod returned aStringbut took anintas a parameter. In this example, the opposite is true. - Changed all of the cases to the names of the months and the return values to
int - The
returnMonthmethod now returns anintrather than aString
Other than those three changes, the program logic is still the same. Break is still found after each case statement, and the default statement will still print out ERROR and exit the program.
Also know that if you try inputting a number in this program, you will get ERROR, as shown below:
run:
Please pick a month:
7
ERROR
BUILD SUCCESSFUL (total time: 4 seconds)
Thanks for reading,
Michael