I made a function that computes the sum of digits of an integer. Trying to make the code shorter, I put in comment the if statement to see if it would still work so I can remove it but I get a StackOverflowError
, why?
This is my code:
public static int sumDigits(int n) {
//if(n%10==n){ return n;}
return n%10+sumDigits(n/10);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(sumDigits(12611));
}
It never returns, but just recurses deeper and deeper.
You do have a return statement, but before returning it needs to compute the value of the expression n%10+sumDigits(n/10)
which involves infinite recursion.
NB: Each time you call the function from itself, the function's context (local variables) are added on top of the stack. The stack has a limited size. Eventually you reach that size and StackOverflowError is the error that's thrown in that condition.