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

134 views Asked by At

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

3

There are 3 answers

0
Deepak Patankar On BEST ANSWER

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.

1
Abra On

In this line of your code (from case 1):

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

The method faktorial is invoked before the println.
That's why the output of faktorial appears first.

I suggest you run your code with a debugger (every good IDE has one) and see for yourself.

0
dariosicily On

The behaviour of your code is correct: System.out.println is a function and so it evaluates its argument before of execution; the evaluation of its argument implies the printing inside the faktorial, then so it is explained the inverted order of the prints from your point of view.