2

Consider following code.

public class Skyler {
Skyler s1=new Skyler();
public static void main(String asd[]){
         Skyler s2=new Skyler();
    }
}

It generates java.lang.StackOverflowError Exception. Why?

Consider following code also.

public class Skyler {
    Skyler s1=new Skyler();
    static Skyler s2=new Skyler();
    Skyler(){
        System.out.println("const");
    }
    public static void main(String sdp[]){}
}

This is also generating same java.lang.StackOverflowError exception. Why?

Is reason same for both Exceptions?

5 Answers 5

3

You are undergone a loop where the constructor calling it self for servaral times until it's overflowed.

For ex :

enter image description here

And the reason is same in both cases. It's calling it self endlessly.

In your both cases there is only once difference that you provided a default no org constructor with a print statement so that you can see that print statement until you got the error.

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

2 Comments

How come is it an ERROR ? Is it not an Exception?
@prateektomar No. There is a difference between error and exception.
2

Each time you create an instance of Skyler, the s1 member of that instance is initialized, which creates another instance of Skyler, which initializes the s1 member of that other instance, which creates another instance of Skyler and so on...

In other words, you have an infinite chain of calls to the Skyler constructor, which causes StackOverflowErr.

3 Comments

Is reason same for exceptions in both the code snippets?
@prateektomar Yes. It is. Added that in my answer. Please read.
@prateektomar Yes. The only difference between the two snippets is where the first instance of Skyler is created (in the main method in the first snippet and in the initialization of a static variable in the second snippet). Once that takes place, the initialization Skyler s1=new Skyler(); causes the infinite constructor calls leading to the exception.
1

Delete Skyler s1=new Skyler();.With your code,Skyler class has a variable whose type is Skyler,then it will be create a Skyler again and again,so StackOverflowException exists.

Comments

1

Check the logic, you create a new Skyler, what does this do? It creates a new Skyler, surprisingly this new Skyler creates another new Skyler. This all comes from your line Skyler s1=new Skyler();(the one that is not static), which recursivly creates endles instances of the Object Skyler.

Comments

1

The class Skyler calls its own constructor. So while creating an instance of Skyler, another instance of Skyler is created and so on... the result is a StackOverflow.

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.