Recursion in java
By: aathishankaran Printer Friendly Format
Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. for example, 3 factorial is 1×2×3, or 6. Here is how a factorial can be computed by use of a recursive method.
class
Factorial {
int fact(int n) {
int result;
if ( n ==1) return 1;
result = fact (n-1) * n;
return result;
}
}
class
Recursion {
public static void main (String args[]) {
Factorial f =new Factorial();
System.out.println(“Factorial of 3 is “ + f.fact(3));
System.out.println(“Factorial of 3 is “ + f.fact(4));
System.out.println(“Factorial of 3 is “ + f.fact(5));
}
}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
If you are unfamiliar with recursive methods, then the operation of fact() may seem a bit confusing. Here is how it works. When fact() is called with an argument of 1, the function returns 1; otherwise it returns the product of fact(n-1)*n. to evaluate this expression, fact() is called with n-1. this process repeats until n equals 1 and the calls to the method begin returning.
To better understand how the fact() method works, let’s go through a short example. When you compute the factorial of 3, the first call to fact() will cause a second call to be made with an argument of 2. this invocation will cause fact() to be called a third time with an argument of 2. This call will return 1, which is then be called a third time with an argument of 1. This call will return1, which is then multiplied by 2 (the value of n in the second invocation). This result (which is 2) is then returned to the original invocation of fact() and multiply by 3 ( the original value of n). This yields the answer, 6. You might find it interesting to insert println() statements into fact() which will show at what level each call is and what the intermediate answers are.
When a method calls itself, new local variables and parameters are allocated storage on the stack, and the method code is executed with these new variables from the start. A recursive call does not make a new copy of the method. Only the arguments are new. As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes at the point of the call inside the method. Recursive methods could be said to “telescope” out and back.
Recursive versions of many routines may execute a bit more slowly than the iterative equivalent because of the added overhead of the additional function calls. Many recursive calls to a method could cause a stack overrun. Because storage for parameters and local variables, it is possible that the stack could be exhausted. If this occurs, the java run-time system will cause an exception. However, you probably will not have to worry about this unless a recursive routine runs wild.
The main advantage to recursive methods is that they can be used to
create clearer and simpler versions of several algorithms than can their
iterative relatives. For example, the QuickSort sorting algorithm is quite
difficult to implement in an iterative way.
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Archived Comments
1. Thx for the explanation, I understand what recursi
View Tutorial By: Tina at 2008-12-15 16:39:27
2. Comment: yes i understood too:D:D perfect and brei
View Tutorial By: eman at 2009-04-21 23:57:26
3. this is really cool......
View Tutorial By: solex at 2009-05-16 04:02:35
4. example is ok, but plz increases the standard of e
View Tutorial By: venky at 2009-05-19 01:29:04
5. i dont understand...i think u be trollin...
View Tutorial By: jamon at 2009-05-19 06:18:21
6. Good explanation but I think there's a slight mist
View Tutorial By: Cheeseman at 2009-05-19 10:12:11
7. Explanation was good and easily comprehendable.
View Tutorial By: Moin Adil at 2009-06-17 04:18:56
8. It a wrong program is not console print 3,4,5
View Tutorial By: pho at 2009-07-27 21:20:39
9. example is good for understand what is the functio
View Tutorial By: Ankit Shukla at 2009-09-17 15:25:17
10. ...indeed its a helpful brief explanation, coz our
View Tutorial By: elaine22 at 2010-01-22 01:27:16
11. Plz can u give me some more examples of recursion.
View Tutorial By: Asadullah at 2010-01-23 06:38:58
12. i find out this example quite heplful thnx adimn..
View Tutorial By: ayaz pathan ( MUET) at 2010-02-21 10:40:18
13. nice...cleared this example....
View Tutorial By: Waqas Mughal at 2010-03-13 21:21:46
14. this is genius.
you are a master of recursi
View Tutorial By: Chandler at 2010-03-26 09:56:08
15. Good Information... Plz give some more examples wi
View Tutorial By: Uetian at 2010-04-01 04:26:55
16. can we do it this procedure by iteration i know th
View Tutorial By: sattar at 2010-05-03 03:00:20
17. Like every other Java recursion example, this exam
View Tutorial By: Uriah at 2010-05-08 18:59:16
18. thank u.actually i want little more...
View Tutorial By: burhan at 2010-07-13 03:46:01
19. The code to show recursion is ok, but the declara
View Tutorial By: Gaurav at 2010-08-08 01:08:27
20. it's real nice explanation
View Tutorial By: Shreya at 2010-09-10 11:24:11
21. thanks alot!
View Tutorial By: gumuruh at 2010-11-06 11:27:18
22. thanks for suppporting us
View Tutorial By: sonia at 2010-11-29 00:46:56
23. some more examples should be given...
View Tutorial By: flora at 2010-12-08 03:32:50
24. Thanks A lot , short and simplified
View Tutorial By: Barakat at 2011-01-20 15:06:00
25. I think u've done well, just that more examples wi
View Tutorial By: Mac at 2011-01-23 10:22:10
26. thanks ....
View Tutorial By: shiva at 2011-02-28 11:16:32
27. Thanks for everything... I'm greeting you from Aze
View Tutorial By: Shahriyar at 2011-04-28 15:49:49
28. Thanks for everything... I'm greeting you from Aze
View Tutorial By: Shahriyar at 2011-04-28 15:54:14
29. i like this a lot
View Tutorial By: raj at 2011-05-06 06:15:36
30. Plz show me how to use main method reccurssively p
View Tutorial By: Jyoti Bankar at 2011-07-14 10:31:53
31. result = fact (n-1) * n;
i didn't got this
View Tutorial By: pp at 2011-08-07 20:20:33
32. result = fact (n-1) * n;
i didn't got this
View Tutorial By: praveen at 2011-08-07 20:22:09
33. recursive programs that ask the user to enter the
View Tutorial By: siyabonga at 2011-08-10 08:34:44
34. give an recursive example using string
View Tutorial By: sauk at 2011-08-22 16:16:41
35. How can you print this using recursion?
View Tutorial By: Menon at 2011-09-08 07:16:02
36. Ghanta cool it contains 9 errors.......!!
View Tutorial By: shweta at 2011-09-16 09:12:53
37. Now what the hell does all this mean???
To
View Tutorial By: Søren at 2011-09-22 03:13:53
38. best example of recursion i ever saw.thanks alot d
View Tutorial By: tariq at 2011-10-04 10:21:49
39. this is a copy citation from book "java the c
View Tutorial By: wiktor at 2011-12-18 21:32:04
40. CTRL+C then CTRL+V :P
Complete Reference ;)
View Tutorial By: Rahul A at 2012-03-21 14:12:56
41. Dear author
u missed check condition for 0(
View Tutorial By: Maroof Ahmad at 2012-03-28 14:59:53
42. It takes me time to understand the process of the
View Tutorial By: Abdullah Ibrahim at 2012-04-11 00:38:23
43. Yes ..! It's good.
You can get the same cod
View Tutorial By: chandra at 2012-05-24 18:58:52
44. Hagti hain.. the complete program has been copy pa
View Tutorial By: Macho Man at 2012-06-21 07:58:03
45. thanks...please give some more examples
View Tutorial By: Iqra at 2012-06-24 18:57:51
46. Thanks for the article. I finally finish my task a
View Tutorial By: bali web at 2012-07-10 13:47:49
47. @Iqra :
You're welcome. Use sites l
View Tutorial By: Macho Man at 2012-07-16 08:02:14
48. the example program that given above for recursion
View Tutorial By: bharathi at 2012-07-17 09:31:14
49. can anyone explain the output of this recursive ex
View Tutorial By: vipul at 2012-08-12 19:41:19
50. Thanks for the explanation. I had read about this
View Tutorial By: Sidharth Sahoo at 2012-09-12 16:26:07
51. This is blatantly plagiarized from Java, The Compl
View Tutorial By: Someone at 2013-01-28 04:53:22
52. See this link to learn <a href="http://jav
View Tutorial By: Sachin at 2013-01-29 03:53:33
53. Declaring int result within the method will change
View Tutorial By: Soph at 2013-02-06 06:11:39
54. class Factorial
{
int fact(int
View Tutorial By: soph at 2013-02-06 06:49:07
55. thank you for code
View Tutorial By: turki at 2013-12-11 13:23:44
56. I don't undrstnd.. cz I think in recurs the method
View Tutorial By: Alina Ali at 2014-11-13 03:06:17
57. thanks!
View Tutorial By: leny at 2014-12-09 04:00:44
58. thanks , but i want it some thing like fibonici se
View Tutorial By: Arpit Agrawal at 2015-01-04 18:34:41
59. it really helped me...thank you...
View Tutorial By: ram at 2015-01-22 20:12:01
60. realy i enjoy it for visit your site. and i unders
View Tutorial By: vinod balot at 2015-02-09 17:43:30
61. great explanations.. some important words are miss
View Tutorial By: Joshua Paul at 2015-04-14 03:43:44
62. nice explanation indeed, but can u please explain
View Tutorial By: ishika at 2015-06-23 09:16:16
63. Thank you!!
View Tutorial By: Diego at 2015-07-16 21:11:58
64. 0's factorial cannot be find out?
View Tutorial By: ketan at 2015-12-29 08:27:23
65. copy from book
View Tutorial By: Roshan at 2016-04-13 13:27:48
66. Great web site. Plenty of useful info here. I am s
View Tutorial By: Market Research at 2017-07-28 05:24:50
67. utaleuef
View Tutorial By: utaleuef at 2017-08-11 05:43:03