Why is the code under the recursive call processed more than once (when the base case is true)?

My code first:

import java.util.Scanner; 

public class recursionQuestion {

  public static void methodB(boolean b) {
    if(b == true) {
      System.out.println("'b' is true!");
    } else {
      methodA();
    }
  }

  public static void methodA() {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter 0 or 1: ");
    int val = keyboard.nextInt();
    boolean b;
    if(val == 0) {
      b = false;
    } else {
      b = true;
    }
    methodB(b);
    System.out.println("Why is this being processed when b is false?");
  }

  public static void main(String[] args) {
    methodA();
  }

}

      

I always thought I figured out recursion, but maybe not. If the user is prompted to enter input and enter "0" x times, why does this code print the line "Why is this processed when b is false?" x number of times?

In other words, why is the code (in methodA()

) below the call being methodB()

processed more than once? Should the call (in methodB()

) methodA()

not return the execution thread to the beginning methodA()

?

+3


source to share


3 answers


When you call methodB(b)

from methodA

when b is false, it triggers a new call methodA

. As soon as the execution of that call methodA

and then the execution of the call methodB

ends, the control falls back to the instance methodA

called methodB

and so your string is printed.

Here's a possible scenario:



methodA
  calls methodB(false)
    calls methodA
      calls methodB(false)
        calls methodA
          calls methodB(true)
            prints "'b' is true!" and returns
          prints "Why is this being processed when b is false?"
      prints "Why is this being processed when b is false?"
  prints "Why is this being processed when b is false?"

      

+4


source


Method A calls method B. After B executes, control returns to A. Therefore, the string is printed.



+1


source


See what recursive calls do.

methodA()
    methodB() [if user entered 0], then b is false
        methodA() [assume a non-zero number is entered]
            methodB()
                "'b' is true!"
        "Why is this being processed when b is false?"

"Why is this being processed when b is false?"

      

No matter what value you put into your call methodB()

, you will always execute the print instruction. This is because the execution point goes back to where the call was made; in this case it will happen immediately after the call methodB()

.

If printing a statement was required as a condition for your recursion, you need to add that as a condition to your recursive step. In this case, these are two methods, more or less bouncing from each other.

+1


source







All Articles