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