Search code examples
javadebuggingsun

Bug in Java when printing factorial recursive method? Output printed before 'printing command'


I am currently learning java and at point of learning recursive. I tried these two identical methods but one of them in my opinion is acting strange. Is it a bug in Java? Or is it just me who can't get the logic.

Does anyone can give explanation about this?

JAVA I Use :

java version "1.8.0_261"

Java(TM) SE Runtime Environment (build 1.8.0_261-b12)

Java HotSpot(TM) Client VM (build 25.261-b12, mixed mode, sharing)

Here is my code:

1st CASE :

public class App {
public static void main(String[] args) {
    int value = 5;

    System.out.println("Factorial " + value + " = " + faktorial(value));
}

public static int faktorial(int value) {
    
    if (value > 1) {
        System.out.print(value + " * ");
    }
    
    if (value == 1) {
        System.out.println("1");
        return 1;
    }

    return value * faktorial(value-1);
}

}

The Output of 1st CASE will be:

5 * 4 * 3 * 2 * 1 <== HERE IS WHERE THING GET STRANGE, IT SHOULD BE PRINTED AFTER 'Factorial 5 = ', NOT BEFORE

Factorial 5 = 120

While in 2nd Case:

public class App {
public static void main(String[] args) {
    int value = 5;

    System.out.print("Factorial " + value + " = "); //HERE IS THE CHANGE
    System.out.println(faktorial(value)); //HERE IS THE CHANGE
}

public static int faktorial(int value) {
    
    if (value > 1) {
        System.out.print(value + " * ");
    }
    
    if (value == 1) {
        System.out.println("1");
        return 1;
    }

    return value * faktorial(value-1);
}

}

The output of 2nd CASE will be :

Factorial 5 = 5 * 4 * 3 * 2 * 1 <== IT IS RUNNING IN CORRECT ORDER

120


Solution

  • The function faktorial is called in the line,

    System.out.println("Factorial " + value + " = " + faktorial(value));
    

    While the function is running it will print all the print statements you have written, and then when you get the return value of function faktorial, then the line "Factorial " + value + " = " + faktorial(value) will be printed.

    Similar case is happening on the second example too, the print statement of the functions is printed first and after the function returns, you will get the return value of the function printed.