Search code examples
javatestingrecursionruntime-errorstack-overflow

Confusing Recursive StackOverflowError program


I wrote down a recursive program in Java (for fun) where a few things are not clear :

public class methodTest
{
    public static double methodTest()
    {
        System.out.println("qwerty") ; // sign that this method is called
        methodTest obj1 = new methodTest() ; // creating an object (perhaps unnessary)
        System.out.println(methodTest.methodTest()) ; // ??!
        return methodTest() ; // returning the same function
    }
}
  1. Why, if the return datatype is double, my BlueJ compiler not showing a syntax error when returning a method ?
  2. How can this program be stopped if the number of times this method is 'recursed' with and without using an incrementing variable ? [I tried using a static int initialised in the class (before methodTest()) and incrementing it in the method but it shows "unreachable statement"]
  3. What is the computer doing when it tries to execute the System.out.println(methodTest.methodTest()) statement ?
  4. Why does the compiler give a syntax error (cannot find symbol - variable obj1) when I replace (in System.out.println(methodTest.methodTest())) .methodTest with .obj1 ?

    Please answer my questions ☝️

Solution

  • Here is one way to approach this.

    Notes:

    • The class exposes a simple method that kicks off the recursion.
    • The recursive method checks for the number of recursions.
    • It returns a hardcoded value because I have no idea what you're actually trying to do.
    public class MySampleClass
    {
        private static double methodTestPrivate(int callIndex)
        {
           //Check for terminating condition
           if (callIndex >= 10)
               return 42.0;
    
           //Recursive call
           return methodTestPrivate(callIndex+1);
        }
    
        public static double methodTest()
        {  
            return methodTestPrivate(0);
        }
    }
    
    public class MyProgram
    {
        public static void main(String[] args)
        {
            System.out.print(MySampleClass.methodTest());
        }
    }