Mohammad Fadin
Mohammad Fadin

Reputation: 579

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

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 :)

Upvotes: 3

Views: 4663

Answers (2)

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

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)

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120188

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.

Upvotes: 15

Related Questions