• Register
1 vote
48 views

Problem:

I have a piece of sample code that throws me back an error “exception in thread "main" java.lang.stackoverflowerror”.

public class TestCode {
     
    public static void recursivePrint(int num) {
        System.out.println("Number: " + num);
         
        if(num == 0)
            return;
        else
            recursivePrint(++num);
    }
     
    public static void main(String[] args) {
        TestCode.recursivePrint(1);
    }
}

I’ve no idea about it. Is there anything wrong with my recursion?

12 7 7
15,250 points

Please log in or register to answer this question.

2 Answers

1 vote
 
Best answer

Solution:

You are right in a sense because the problem occurred in your recursion.
The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique but must be used with caution, in order for the StackOverflowError to be avoided.

In your case you defined a recursive method, named recursivePrint that prints an integer and then, calls itself, with the next integer as an argument. The recursion ends once we invoke the method, passing 0 as a parameter. Anyway, in your code it started printing numbers from 1 and so on, the recursion will never terminate.

13 9 6
94,240 points
0 votes

Solution:

Your algorithm is exquisite. But int is too small for your computations, it fails for this input:

printSyra(113383, 1);

At some point integer swamps to negative value and your execution goes instance, recursing infinitely. Alter int num to long num and you'll be exquisite - for some time. Afterwards you'll require BigInteger.

The longest advancement for any primary starting number less than 100 million is 63,728,127, which has 949 steps. For begining numbers less than 1 billion it is 670,617,279, with 986 steps, and for numbers less than 10 billion it is 9,780,657,630, with 1132 steps.

The complete number of steps is identical to maximum nesting level (stack depth) you can anticipate. So even for relatively big numbers StackOverflowError should not occur. Have a look at this execution employing BigInteger:

private static int printSyra(BigInteger num, int count) {
    if (num.equals(BigInteger.ONE)) {
        return count;
    }
    if (num.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
        return printSyra(num.divide(BigInteger.valueOf(2)), count + 1);
    } else {
        return printSyra(num.multiply(BigInteger.valueOf(3)).add(BigInteger.ONE), count + 1);
    }
}

It performs even for very big values:

printSyra(new BigInteger("9780657630"), 0)  //1132
printSyra(new BigInteger("104899295810901231"), 0)  //2254

The easiest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers imply the code that is being recursively named. At one time you detect these lines, look for the terminating condition (base condition) for the recursive calls.

At one time you have verified that the recursion is executed exactly, you can rise the stack’s size in order to approve a larger number of invocations. The stack size can be increased by altering the settings of your compiler.

What is StackOverFlowError?

At the time a method call is called by a Java application, a stack frame is situated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address explains the execution point from which, the program execution shall continue after the invoked method returns. In case there is no space for a new stack frame then, the java.lang.StackOverflowError is thrown by the Java Virtual Machine (JVM).

Causes to happens java.lang.StackOverFlowError

  • Recursion : A method calls itself at the time it’s execution and method calling stack reach to max limit of JVM.  Example 1
  • Circular Dependency on method calling. Example 2

A method may not declare such errors in its throw clause, since these errors are abnormal conditions that shall never happen.

Constructors

  • StackOverflowError(): Constructs a StackOverflowError with no detail message.
  • StackOverflowError(String s): Constructs a StackOverflowError with the specified detail message.

Recusrsion StackOverFlowError Example

In this under recursion factorial of number example , I have commented out the recursion terminating condition to create StackOverFlowError.

package com.exceptions.errors;
 
public class StackOverFlowErrorExample {
 
    public static void main(String[] args) {
        RecursionExample recursion=new RecursionExample();
        System.out.println(recursion.fact(7));
    }
}
 
class RecursionExample
{
    public int fact(int n){
//Uncomment this condition to recursion terminating condition
//      if( n == 0 ){
//          return 1;
//      }
        return n * fact(n-1);
    }
}

Circular Dependency StackOverFlowError Example

In this example, we defined two classes, Company and Employee. The class Company holds one instance of the Employee class, while, the Employee class holds one instance of the Company class. In this way, we have a circular dependency between these two classes. Besides, every toString() method, invite the similar toString() method of the other class, and so on, which results in a java.lang.StackOverflowError.

package com.exceptions.errors;
 
public class StackOverFlowExample2 {
 
    public static void main(String[] args) {
        Company company = new Company();
        System.out.println(company.toString());
 
    }
}
 
class Company {
    private int budget;
    private Employee employeeInstance = null;
 
    public Company() {
        budget = 0;
        employeeInstance = new Employee();
    }
 
    @Override
    public String toString() {
        return "FacingIssueOnIT : Company";
    }
}
 
class Employee {
    private int salary;
    private Company companyInstance = null;
 
    public Employee() {
        salary = 10;
        companyInstance = new Company();
    }
 
    @Override
    public String toString() {
        return "FacingIssueOnIT : Employee";
    }
}

How to deal with the StackOverflowError

  • In case of recursion, always apply terminating condition and that should fulfill in some cases so that method call not go to successive call.
  • To reconnoiter the stack trace and detect the repeating pattern of line numbers. These line numbers show the code being recursively called. At one time you detect these lines, you should gingerly inspect your code and understand why the recursion never terminates.
  • In case recursion and terminating state are in position exactly.  You can raise the stack’s size, in order to approve a larger number of invitation. Default thread stack configuration rely on JVM few may equals to either 512KB, or 1MB. You can raise the thread stack size emplying the -Xss flag. This flag can be seclude either through the project’s configuration, or through the command line. The format of the -Xss argument is:
     -Xss[g|G|m|M|k|K]
10 6 4
31,120 points

Related questions

0 votes
1 answer 15 views
15 views
Problem: I have a piece of code and I could not figure out why it is giving me Exception in thread "main" java.lang.StackOverflowError. I know the problem lies with the recursion. The error does not occur if the input is a small value, example: 5. But when the ... 65) at Test.printSyra(Test.java:60) at Test.printSyra(Test.java:60) at Test.printSyra(Test.java:60) at Test.printSyra(Test.java:60)
asked Feb 2 Ali 4.4k points
0 votes
1 answer 13 views
13 views
I know the problem lies with the recursion.
asked Jan 2 TeamScript 13.5k points
0 votes
1 answer 10 views
10 views
Problem: inputs the amount of minutes the user enters and calculates the grand total by adding the CostForMinutes and BasePlanCost. CostForMinutes is calculated by multiplying the minutes the user enters and the BaseCostPerMinute. The out is all the numbers outputted ... this error exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String can anyone help me out?
asked 3 days ago Ali 4.4k points
0 votes
1 answer 6 views
6 views
Problem: I'm getting the exception java.lang.ClassNotFoundException when I am trying to run my code, I'm getting Error java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native ... ) at java.lang.Class.forName(Class.java:169) at Simple.MyProg.main(MyProg.java:15) What am I doing wrong?
asked 3 days ago Ali 4.4k points
0 votes
1 answer 4 views
4 views
Problem: I am getting the error as mentioned below, while running the feed utility. I am trying to load an image "logo.png". The slf4j jar file is also available in the runtime classpath. But still I am getting this error.
asked 4 days ago Ali 4.4k points
0 votes
1 answer 4 views
4 views
Problem: I am new to programming so I apologize beforehand. I am running a program and am having a problem with the System.out.printf method in Java. I know everything else in the program is working correctly (tested it). However this does not ... Unknown Source) at java.io.PrintStream.format(Unknown Source) at java.io.PrintStream.printf(Unknown Source) at Advisor_Score.main(Advisor_Score.java:17)
asked 5 days ago Ali 4.4k points
0 votes
1 answer 9 views
9 views
Problem: public class dereks { public static void main (String [] args){ int array [] = {1,2,3,5,6,7}; int sum =0; for(int counter=0; counter<=array.length; counter++){ sum+=array[counter]; } System.out.println(sum); } } Can anyone tell ... I can't understand why I'm getting the error message "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at dereks.main(dereks.java:7)" .
asked 5 days ago Ali 4.4k points
0 votes
1 answer 17 views
17 views
Problem: I am a beginner to programming. I'm a few weeks into my first programming class, so please bear with me. I am not a person to ask for help, so I have searched for an answer extensively with no luck. This is also my first time posting ... correct for future posts. This is what I got while running the program. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:50 on line 23
asked 5 days ago Ali 4.4k points
0 votes
1 answer 19 views
19 views
Problem: The following program is throwing error: public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World!"); } } CLASSPATH C:\Program Files\Java\jdk1.6.0_18\bin\ Path C:\Program Files\Java\jdk1.6.0_18\bin\ JAVAHOME C:\Program Files\Java\jdk1.6.0_18\bin Can you please tell me the root cause?
asked 6 days ago Ali 4.4k points