I am confused as to how Java is running this specific code. I am comfortable with the Fibonacci sequence but not exactly with how to grapple my mind to the way this specific method is running. So obviously I'm returning 0 if n is 0 and returning 1 if n is 1. Now let us say I pass 3 for n. We return fib(2) + fib(1). How does it know what fib(2) is if it never calculated that in the first place? Does it go through the whole function again to find out what fib(2) is? When does it stop? My mind is going to blow up.
public static int fib(int n){
if (n == 0){
return 0;
}
else if (n == 1){
return 1;
}
return (fib(n-1) + fib(n-2));
}