Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
Now Reading
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Factorial calculations are fundamental operations in mathematics and computer science.
For instance, let's calculate the factorial of 7 (7!). By multiplying all positive integers less than or equal to 7, we get: 7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040.
Therefore, the factorial of 7 is equal to 5040.
Java programming offers a variety of methods to compute the factorial of a number. Among them, the recursive method stands out due to its utilization of a powerful concept known as recursion. This technique involves a function invoking itself to tackle smaller iterations of the same problem until it arrives at a base case. With its ability to decompose the problem into manageable subproblems, recursive factorial computation is not only efficient, but also aesthetically pleasing and comprehensible to most programmers.
In this article, we shall examine the Java recursive method for computing a number's factorial. We'll look at how it's used, talk about the benefits and trade-offs it has over the iterative approach, and assess the time and spatial complexity. You will acquire a useful skill for solving factorial problems successfully and quickly by learning the recursive method for factorial computations.
In this in-depth tutorial, we will cover a variety of topics related to calculating the factorial in Java by using recursion. To help you get a better grasp of the material, we will provide in-depth explanations as well as examples in the form of code.
Before we dive into the recursive method, let's first review how to calculate the factorial using a loop in Java. Below is an example code snippet:
This program prompts the user to enter a number and calculates its factorial using a `for` loop. The result is then displayed on the console.
If you run the FactorialUsingLoop program and provide an input number, it will calculate and print the factorial of that number. Here's an example:
Input:
Output:
Now, let's explore factorials using recursion in Java. Here's the Java code for finding the factorial of a number using recursion:
This program defines a recursive method, `calculateFactorial`, that takes an integer `number` as input and returns its factorial. The method makes recursive calls by decreasing the value of `number` until it reaches the base case of 0 or 1.
Input:
Output:
Explanation:
The program implements a factorial calculation using recursion. The calculateFactorial() method takes an integer number as input and returns the factorial of that number.
In the calculateFactorial() method, we check for base cases where the input number is 0 or 1. If the number is 0 or 1, the factorial is 1. Otherwise, it recursively calls itself with the number - 1 and multiplies the result by the current number. This recursive process continues until it reaches the base case.
In the main() method, we accept user input for the number using the Scanner class. We then call the calculateFactorial() method with the input number and store the result in the factorial variable. Finally, we display the calculated factorial using System.out.println().
To better understand the recursive factorial program, let's consider an example. Suppose we want to find the factorial of 5. Here is how the recursive calls would unfold:
The final result is 120, which is the factorial of 5.
Understanding the time and space demands of the recursive factorial approach is an essential component of using this method. The recursive procedure has a linear time complexity of O(n), which indicates that it does n calls inside of its own recursion, where n is the number that was provided as input. Because additional memory is needed to store the recursive call stack, the recursive method has a linear space complexity with a value of O(n) when compared to other methods' potential levels of space complexity.
Now that we've covered the iterative strategy, let's take a look at how the recursive method stacks up against it. In the iterative technique, the factorial is computed by using a loop, but in the recursive method, the factorial is computed by utilizing recursive function calls. Both approaches will result in the same output; however, the one you choose to use will be determined by the particular necessities of your program. When efficiency and space optimization are of the utmost importance, the iterative method is likely to be the most appropriate choice, particularly for large input numbers. On the other hand, the recursive technique provides a solution that is both more brief and more obvious.
When contrasting the linear (iterative) method with the recursive method, it is essential to take into account the benefits and drawbacks of each approach. The linear technique offers easy implementation in addition to improved space efficiency. By repeatedly going through the numbers, it computes the factorial in a straightforward manner. On the other hand, the recursive method reduces the issue at hand to a series of more manageable sub issues, which ultimately results in a solution that is more elegant but requires a greater amount of memory.
When implementing factorials using recursion in Java, it's crucial to handle edge cases to ensure the correctness and reliability of the program. Here are some common edge cases to consider:
1. Handling Negative Numbers: The factorial operation is only defined for non-negative integers. Therefore, if the input number is negative, we can throw an IllegalArgumentException to indicate an invalid input. Here's an example:
This example demonstrates the handling of negative numbers by throwing an exception and providing an informative error message when calculating the factorial recursively.
public class RecursiveFactorial {
public static int calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative numbers");
}
return factorialHelper(n);
}
private static int factorialHelper(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorialHelper(n - 1);
}
public static void main(String[] args) {
int number = -5;
try {
int factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
In this example, we have added an initial check in the calculate factorial () method to validate whether the input number is negative. If the number is less than 0, we throw an IllegalArgumentException with a custom error message stating that the factorial is not defined for negative numbers.
The calculate factorial () method then calls the factorialHelper() method, which performs the recursive calculation of the factorial. The factorialHelper() method follows the recursive factorial algorithm and calculates the factorial of a non-negative number.
In the main() method, we set the number variable to -5, which is a negative number. When we attempt to calculate the factorial using the calculate factorial () method, an IllegalArgumentException will be thrown if the input is negative. We catch the exception using a try-catch block and display the error message using e.getMessage(). The output will be "Factorial is not defined for negative numbers".
2. Handling Zero: The factorial of zero is defined as 1. So, when the input number is zero, we can simply return 1.
Here's an example:
In Python, we can implement the recursive factorial calculation using a function. The function will call itself with a smaller input until it reaches the base case. Here's a factorial using recursion in java example for Python:
In this code, the `factorial` function takes an input `n`. If `n` is 0, it returns 1 (base case). Otherwise, it recursively calls itself with `n - 1` and multiplies the result by `n`. This recursive approach provides an elegant solution to calculate the factorial in Python.
Similarly, we can calculate the factorial using recursion in the C programming language.
Here's an example:
In this code, the `factorial` function is defined to recursively calculate the factorial. It follows the same logic as in Python, where the base case is when `n` is 0, returning 1. Otherwise, it recursively calls itself with `n - 1` and multiplies the result by `n.` The main function demonstrates the usage of the `factorial` function by calculating the factorial of a given number.
In JavaScript, we can also use recursion to calculate the factorial of a number.
Here's an example:
In this code, the `factorial` function is defined using recursion. It checks if `n` is 0 (the base case) and returns 1. Otherwise, it recursively calls itself with `n - 1` and multiplies the result by `n`. The result is calculated using the `factorial` function and displayed using `console.log()`.
Let’s look at the concept with the following example:
In this program, we first create a `Scanner` object to read user input from the console. The user is prompted to enter a non-negative integer using `System.out.print()`. The input is then stored in the `number` variable using `scanner.nextInt()`. We close the scanner after we have obtained the input.
Next, we pass the `number` variable to the `calculateFactorial()` method, which uses recursion to calculate the factorial. The base case is when `n` is 0, in which case it returns 1. Otherwise, it recursively calls itself with `n - 1` and multiplies the result by `n.`
Finally, we display the calculated factorial using `System.out.println().`
Example:
In this example, the program prompts the user to enter a non-negative integer. Let's say the user enters 5. The program then calculates the factorial of 5 using the calculateFactorial() method. The output is displayed as "Factorial of 5 is: 120". This means that the factorial of 5 is 120.
The program uses recursion to calculate the factorial. The calculateFactorial() method checks if the input number is 0. If it is, the method returns 1, as the factorial of 0 is defined as 1. Otherwise, it recursively calls itself with the number decremented by 1 and multiplies it by the current number. This process continues until the base case is reached (0), resulting in the factorial calculation.
In conclusion, we compared the recursive and iterative Java methods for computing integer factorials. Program needs will dictate which method is used, even if both work. Recursive solutions are elegant and simple because they divide the problem down into smaller subproblems until the base case is reached. Recursively calling the original method uses more memory. When dealing with large input amounts or optimizing space, the iterative method is more efficient and applicable.
1. Can we calculate factorials using recursion in languages other than Java?
Yes, the recursive approach to calculating factorials can be implemented in other programming languages such as Python, C, and JavaScript. Recursion is a general concept not limited to Java.
2. What happens if we enter a negative number as input?
The factorial is defined only for non-negative integers. If a negative number is entered, the recursive method will keep making recursive calls indefinitely, resulting in a stack overflow error. It's crucial to handle such cases by adding input validation to ensure a valid input range.
3. Is there a limit to the input number for calculating the factorial using recursion?
The limit on the input number depends on the system's memory and the maximum recursion depth allowed by the programming language. For very large input numbers, the recursive approach may encounter a stack overflow error. In such cases, it's advisable to consider alternative approaches, such as an iterative or optimized solution.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...