0

I am getting StackOverflow error while executing the below:

public class StackOverflow7 {
    StackOverflow7 obj = new StackOverflow7();
    int finalCount = 0;
    public static void main(String[] args) {
        for(int i = 1 ; i <= 5 ; i++)
        System.out.println(i);

        StackOverflow7 localObj = new StackOverflow7();
        localObj.count(88);
        System.out.println("Final Count :: " + localObj.finalCount);
    }

    private void count(int num){
        finalCount = finalCount + num;
    }
}

3 Answers 3

4

This line:

StackOverflow7 obj = new StackOverflow7();

is always called when you create an object of StackOverflow7, which you are doing in this line itself. Thus, this line recursively calls itself, until you get a StackOverflow error.

Sign up to request clarification or add additional context in comments.

Comments

1

You get the stack overflow because of this line: StackOverflow7 obj = new StackOverflow7();. Whenever you create a new instance, it is called and thus you create a new instance and create a new instance and so on. In your stack trace you should thus see a lot of <clinit> lines.

You start the whole thing by calling StackOverflow7 localObj = new StackOverflow7(); in your main method.

To fix this either make obj a static field or remove it altogether, since you're not using it anyways.

Comments

0

Because of this line:

StackOverflow7 obj = new StackOverflow7();

Every time you create a new object this line will executet and try to create an other object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.