Recursion in java

By: aathishankaran  

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.




Archived Comments

1. utaleuef
View Tutorial          By: utaleuef at 2017-08-11 05:43:03

2. Great web site. Plenty of useful info here. I am sending
it to several friends ans also shar

View Tutorial          By: Market Research at 2017-07-28 05:24:50

3. copy from book
View Tutorial          By: Roshan at 2016-04-13 13:27:48

4. 0's factorial cannot be find out?
View Tutorial          By: ketan at 2015-12-29 08:27:23

5. Thank you!!
View Tutorial          By: Diego at 2015-07-16 21:11:58

6. nice explanation indeed, but can u please explain me the type of recursion?
View Tutorial          By: ishika at 2015-06-23 09:16:16

7. great explanations.. some important words are missing for example... calling itself REPEATED... ther
View Tutorial          By: Joshua Paul at 2015-04-14 03:43:44

8. realy i enjoy it for visit your site. and i understand this resursion function.
View Tutorial          By: vinod balot at 2015-02-09 17:43:30

9. it really helped me...thank you...
View Tutorial          By: ram at 2015-01-22 20:12:01

10. thanks , but i want it some thing like fibonici series
wher it returns(fib(----)+fib(----)
View Tutorial          By: Arpit Agrawal at 2015-01-04 18:34:41

11. thanks!
View Tutorial          By: leny at 2014-12-09 04:00:44

12. I don't undrstnd.. cz I think in recurs the method again n again calls itself.. but in this pgm ther
View Tutorial          By: Alina Ali at 2014-11-13 03:06:17

13. thank you for code
View Tutorial          By: turki at 2013-12-11 13:23:44

14. class Factorial
{
int fact(int n)
{
if ( n ==1) retu

View Tutorial          By: soph at 2013-02-06 06:49:07

15. Declaring int result within the method will change the value of result each time you run the method,
View Tutorial          By: Soph at 2013-02-06 06:11:39

16. See this link to learn <a href="http://javarevisited.blogspot.com.ar/2012/12/recursion-in-ja
View Tutorial          By: Sachin at 2013-01-29 03:53:33

17. This is blatantly plagiarized from Java, The Complete Reference.
View Tutorial          By: Someone at 2013-01-28 04:53:22

18. Thanks for the explanation. I had read about this topic earlier but I wasn't able comprehend it. Now
View Tutorial          By: Sidharth Sahoo at 2012-09-12 16:26:07

19. can anyone explain the output of this recursive example???
class a
{
static int

View Tutorial          By: vipul at 2012-08-12 19:41:19

20. the example program that given above for recursion program is not executed currectly, thanks for tha
View Tutorial          By: bharathi at 2012-07-17 09:31:14

21. @Iqra :

You're welcome. Use sites like stack overflow and check out Complete Referenc

View Tutorial          By: Macho Man at 2012-07-16 08:02:14

22. Thanks for the article. I finally finish my task about it.. and thanks for clear explanation.. :D
View Tutorial          By: bali web at 2012-07-10 13:47:49

23. thanks...please give some more examples
View Tutorial          By: Iqra at 2012-06-24 18:57:51

24. Hagti hain.. the complete program has been copy pasted from JAVA Complete Reference including explan
View Tutorial          By: Macho Man at 2012-06-21 07:58:03

25. Yes ..! It's good.
You can get the same code here as well.

http://enrichjava.b

View Tutorial          By: chandra at 2012-05-24 18:58:52

26. It takes me time to understand the process of the factorial example. I think the explanation would b
View Tutorial          By: Abdullah Ibrahim at 2012-04-11 00:38:23

27. Dear author
u missed check condition for 0(Zero)
so u must be write in if(n==0 || n==1

View Tutorial          By: Maroof Ahmad at 2012-03-28 14:59:53

28. CTRL+C then CTRL+V :P
Complete Reference ;)

View Tutorial          By: Rahul A at 2012-03-21 14:12:56

29. this is a copy citation from book "java the complete reference 7th edition" by herbert sch
View Tutorial          By: wiktor at 2011-12-18 21:32:04

30. best example of recursion i ever saw.thanks alot dear
View Tutorial          By: tariq at 2011-10-04 10:21:49

31. Now what the hell does all this mean???
To better understand how the fact() method works, let

View Tutorial          By: Søren at 2011-09-22 03:13:53

32. Ghanta cool it contains 9 errors.......!!
View Tutorial          By: shweta at 2011-09-16 09:12:53

33. How can you print this using recursion?


tab
b
ab
tab

View Tutorial          By: Menon at 2011-09-08 07:16:02

34. give an recursive example using string
View Tutorial          By: sauk at 2011-08-22 16:16:41

35. recursive programs that ask the user to enter the name of the file or path
View Tutorial          By: siyabonga at 2011-08-10 08:34:44

36. result = fact (n-1) * n;
i didn't got this concept ..
if i put n=3 then the answer is

View Tutorial          By: praveen at 2011-08-07 20:22:09

37. result = fact (n-1) * n;
i didn't got this concept ..
if i put n=3 then the answer is

View Tutorial          By: pp at 2011-08-07 20:20:33

38. Plz show me how to use main method reccurssively plz
View Tutorial          By: Jyoti Bankar at 2011-07-14 10:31:53

39. i like this a lot
View Tutorial          By: raj at 2011-05-06 06:15:36

40. Thanks for everything... I'm greeting you from Azerbaijan,Baku...
View Tutorial          By: Shahriyar at 2011-04-28 15:54:14

41. Thanks for everything... I'm greeting you from Azerbaijan,Baku...
View Tutorial          By: Shahriyar at 2011-04-28 15:49:49

42. thanks ....
View Tutorial          By: shiva at 2011-02-28 11:16:32

43. I think u've done well, just that more examples will have been very appropriate.
View Tutorial          By: Mac at 2011-01-23 10:22:10

44. Thanks A lot , short and simplified

Barakat (Ashesi university Ghana)

View Tutorial          By: Barakat at 2011-01-20 15:06:00

45. some more examples should be given...
View Tutorial          By: flora at 2010-12-08 03:32:50

46. thanks for suppporting us
View Tutorial          By: sonia at 2010-11-29 00:46:56

47. thanks alot!
View Tutorial          By: gumuruh at 2010-11-06 11:27:18

48. it's real nice explanation
View Tutorial          By: Shreya at 2010-09-10 11:24:11

49. The code to show recursion is ok, but the declaration of variables should be done outside the funct
View Tutorial          By: Gaurav at 2010-08-08 01:08:27

50. thank u.actually i want little more...
View Tutorial          By: burhan at 2010-07-13 03:46:01

51. Like every other Java recursion example, this example uses either (a) factorial or fibonacci, or (b)
View Tutorial          By: Uriah at 2010-05-08 18:59:16

52. can we do it this procedure by iteration i know that is simple way but it's complicated thanks
View Tutorial          By: sattar at 2010-05-03 03:00:20

53. Good Information... Plz give some more examples with explaination
View Tutorial          By: Uetian at 2010-04-01 04:26:55

54. this is genius.
you are a master of recursion

View Tutorial          By: Chandler at 2010-03-26 09:56:08

55. nice...cleared this example....
View Tutorial          By: Waqas Mughal at 2010-03-13 21:21:46

56. i find out this example quite heplful thnx adimn......:)
View Tutorial          By: ayaz pathan ( MUET) at 2010-02-21 10:40:18

57. Plz can u give me some more examples of recursion...
thnx alot for the explanation
it

View Tutorial          By: Asadullah at 2010-01-23 06:38:58

58. ...indeed its a helpful brief explanation, coz our instructor want us to explore more deeper the rec
View Tutorial          By: elaine22 at 2010-01-22 01:27:16

59. example is good for understand what is the function of recursion but i think in additional there is
View Tutorial          By: Ankit Shukla at 2009-09-17 15:25:17

60. It a wrong program is not console print 3,4,5
but editor make up ...

View Tutorial          By: pho at 2009-07-27 21:20:39

61. Explanation was good and easily comprehendable.
View Tutorial          By: Moin Adil at 2009-06-17 04:18:56

62. Good explanation but I think there's a slight mistake in the output. It give's the "intended&qu
View Tutorial          By: Cheeseman at 2009-05-19 10:12:11

63. i dont understand...i think u be trollin...
View Tutorial          By: jamon at 2009-05-19 06:18:21

64. example is ok, but plz increases the standard of example a little bit high with real time. It's equa
View Tutorial          By: venky at 2009-05-19 01:29:04

65. this is really cool......
View Tutorial          By: solex at 2009-05-16 04:02:35

66. Comment: yes i understood too:D:D perfect and breif explanation..thnx alot
eman from (german

View Tutorial          By: eman at 2009-04-21 23:57:26

67. Thx for the explanation, I understand what recursion means in java now.
View Tutorial          By: Tina at 2008-12-15 16:39:27


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial