What will be the result of compilation and execution of the following code:

public class Test {
    static int fact(int x) {
        if (x == (-2)) 
            return -2;
        return (fact(x-1) * x);
    }
    public static void main(String[] args) {
        System.out.println(Test.fact(2));
    }
}
Explanation
While running recursively result will be evaluated in this order:

fact(2) = 
fact(1) * 2 = 
fact(0) * 1 * 2 = 
fact(-1) * 0 * 1 * 2 = 
fact(-2) * (-1) * 0 * 1 * 2 = 
(-2) * (-1) * 0 * 1 * 2 = 0

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback