Home > Enterprise >  Encountered Java.lang.StackOverflowError: null while executing the following code
Encountered Java.lang.StackOverflowError: null while executing the following code

Time:11-13

class Generate//to print all numbers from 1000 to 9999 whose digits are in ascending order
{
    private boolean order(int n, int i)//checks if the digits of given number are in ascending order
    {
        if(n==0)
        return true;
        if(n<i)
        return(order(n/10,n));
        return false;
    }
    void show(int n)//recursive function to generate numbers from 1000 to 9999
    {
        if(n>9999)//base case for recursor
        System.out.print("");
        else
        {
            if(order(n,10))//if digits are in ascending order, prints the number
            System.out.println(n);
            show(n 1);//recursive call
        }
    }
}

The above code was supposed to print all numbers from 1000 to 9999. Code compiled and run but received a runtime exception: Java.lang.StackOverflowError: null. Would a try catch block fix my problem? This is my first time posting here hence I am not familiar with the question etiquette, please correct me if I'm wrong.

CodePudding user response:

Java (and most of the programming languages) provides finite number of memory slot to be used for stack-frame, when your program/code reaches that limit it throws the StackOverFlow error.

In your case, your program reaches that limit before coming to base condition.

My take on this -

  1. Do not use Recursive approach until and unless you are splitting your problem into acceptable sub-problems.

  2. this shows you how you can increase stack-frame-size to be used by the JVM for a particular thread.

CodePudding user response:

In my opinion StackOverFlow is due to double recursion i.e both show(), and order() are recursive... I think show() does not need to be recursive. modified your code as under:

 public static void main(String[] args) {
        /
        new Generate().show(); // added main function to get output or exception.. you can omit it and call Generate().show() at the point u require.
    }
}
    class  Generate//to print all numbers from 1000 to 9999 whose digits are in ascending order
{
    private boolean order(int n, int i)//checks if the digits of given number are in ascending order
    {
        if(n==0)
        return true;
        if(n<i)
        return(order(n/10,n));
        return false;
    }
    void show()//function to generate numbers from 1000 to 9999 - WITHOUT Recursion
    {
        int n = 1000;
        while(n<=9999)
        { if(order(n,10))//if digits are in ascending order, prints the number
            System.out.println(n);
            n  ;
        }
    }
}

and here is output: (showing first 7 iterations only) 1234 1235 1236 1237 1238 1239 1245 .......

  • Related