Steve Dav
Steve Dav

Reputation: 43

Calling to the same method inside that same method

This is a pretty stupid, but simple question. I am just wondering in Java if you can call to a method, let's say the method:

get(x)

Inside the method:

get(x)

I'm not even sure how you would do this if you can do it. However, I believe that you can't call to a method in that same method. I just want some clarification on the matter. Thank you!

Upvotes: 1

Views: 9906

Answers (1)

nits.kk
nits.kk

Reputation: 5316

A method calling itself is Recursion. Each method call is done using a stack. When a method is invoked, its local variables are held in a stack. Each method invokation is is composed of the local state for that particular invokation, and each local state is pushed in stack of the running thread. After completion of one instance of method invokation the state is popped from the stack

If a method A invokes a method B then state of method A are saved in stack and once execution of method B is completed then method A resumes its further execution with the saved values of its local variables from the Stack.

Same concept is used in recursion as well. Here we have both A and B methods as same. Each invokation of a method can be considered to be a new method call and the calling method's local variables are saved in stack. Once the callee method executes the control comes back to the caller method and execution proceeds ahead.

Usually Recursion consists of

  1. Method parameter upon which each method call will be based upon. Each callee instance of method will modify the parameter and call the method with new value of the parameter.

  2. a base case(some value of parameter) which when reached the recursive call is broken and control reaches back to the callee instance of the method.

  3. number of options for the parameter. (this may be a series like parameter incremented or decremented by a defined step, divided or multiplied by a defined number if parameter is a number, etc)

  4. recursive call with new parameter

  5. Back track, reset the parameters if needed.

Upvotes: 9

Related Questions