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
}
}
- Why, if the return datatype is
double, my BlueJ compiler not showing a syntax error when returning a method ? - 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 (beforemethodTest()) and incrementing it in the method but it shows "unreachable statement"] - What is the computer doing when it tries to execute the
System.out.println(methodTest.methodTest())statement ? - Why does the compiler give a syntax error (
cannot find symbol - variable obj1) when I replace (inSystem.out.println(methodTest.methodTest())).methodTestwith.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());
}
}