Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading