Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java beginner Question: Can a method be called inside it self?

Tags:

java

recursion

I had an exam today and there was a question which I don't really remember the exact code.

But what I do remember that inside the method exampleMethod(int num) there was a line calling the method itself inside the method.

I want to know can a method be called inside it self? because it was a multiple choice question and they wanted from us to find the output.

I hope my question is clear.

Thanks SOF :)

like image 971
Mohammad Fadin Avatar asked Feb 03 '26 12:02

Mohammad Fadin


2 Answers

Sure it can. When you do that it's called recursion. Be careful that you have an exit condition or you will get a stack overflow.

for example

int iAmRecursive(int num) {
   if (num > 10) // break out at some condition; i.e. don't recurse
       return num; // return so the recursion doesn't continue

   iAmRecursive(num + 1); // I didn't break out, so continue to recurse.
}

EDIT -- here is the same example but with a different break-out, to compliment @Ted's comment

int iAmRecursive(int num) {
   if (num <= 10) // only continue under certain condition
       iAmRecursive(num + 1); 

   // When I get here, I implicitly break out by not recursing.
}

however I prefer to always be as explicit as possible, so I would explicitly break out as in the first example, if possible.

like image 177
hvgotcodes Avatar answered Feb 06 '26 02:02

hvgotcodes


A nice example of recursion is a method to compute a factorial.

public static long factorial(int i)
{
    if (i == 1) return 1;
    return factorial(i - 1) * i;
}

Then invoke it simply like this:

long f = factorial(10); // equals 10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 (* 1)
like image 22
Martijn Courteaux Avatar answered Feb 06 '26 01:02

Martijn Courteaux