-4

I was practicing java, and i wrote this program and once i run it, this raise an error StackOverFlow Error why ?

public class MyClass { 

   MyClass  s=new MyClass();
    public static void main(String args[]) {
         MyClass  s1=new MyClass();

        System.out.println("Sum of x+y = ");
    }
}

Exception StackTrace :

Exception in thread "main" java.lang.StackOverflowError
    at com.practice.java.dev.MyClass.<init>(MyClass.java:3)
    at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
    at com.practice.java.dev.MyClass.MyClass.<init>(MyClass.java:5)
    at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
    at com.practice.java.dev.MyClass.<init>(MyClass.java:5)
    at com.practice.java.dev.MyClass.<init>(MyClass.java:5)

Why so, Please explain it in deep ??

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
  • 3
    Your class `MyClass` has a field `s` that is initialised to contain another instance of `MyClass`. And that instance has to contain another instance, and so on until stack overflow. You're not using that field; you could just delete it. – khelwood Jul 12 '18 at 12:22
  • I think you will find a previous [discussion](https://stackoverflow.com/questions/3679832/java-stackoverflowerror-when-local-and-instance-objects-creation) on this. – soufrk Jul 12 '18 at 12:25

2 Answers2

3

The first line of your main creates a MyClass instance:

MyClass  s1=new MyClass();

Before the MyClass constructor's body is executed, all the instance variables are initialized, which executes:

MyClass s = new MyClass();

This creates a second instance of MyClass, and before that constructor's body is executed, the instance variable s of that second instance is initialized, leading to the creation of a 3rd MyClass instance. And so on...

In other words, you are creating an infinite number of MyClass instances recursively. This leads to an infinite recursion and StackOverflowError.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

You're creating a class of MyClass inside MyClass, which results in an "infinite" depth of these classes getting created all the time, until you get StackOverflow.

ech0
  • 512
  • 4
  • 14