0

Why this program gives this exception

"Exception in thread "main" java.lang.StackOverflowError at com.Test.<init>(Test.java:5)"

Code:

public class Test {

    Test t  = new Test();

    public static void main(String[] args) {
        Test t  = new Test();
    }
}
Guy
  • 46,488
  • 10
  • 44
  • 88
Somu Bolla
  • 27
  • 1
  • 2
    Each time you create a new instance of `Test` you'll create another instance of `Test` (that `Test t = new Test();` field). That's why you create a stack overflow. As for the flow you should probably grab some basic tutorial. – Thomas Aug 14 '19 at 10:48

3 Answers3

1

It happens because you initialize an instance level variable as an instance of the class where it is defined itself which results in the endless recursion and the JVM throws the StackOverflowError:

  • A new instance of Test in the main method creates Test which initializes Test as the instance level variable which creates Test which initializes Test as the instance level variable etc...

To fix it, remove the first line of the code in the class and use the following:

public class Test {

    public static void main(String[] args) {    // this static method is called once upon 
        Test t  = new Test();                   // the start and creates an instance once
    }
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

Every class instance calling new class instance (endlessly), and therefore the StackOverflowError

Just remove the unused field from class:

public class Test {   

    public static void main(String[] args) {
        Test t  = new Test();
    }
}
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

StackOverFlowError is coming because you are creating same class object as instance level variable. So whenever you create an instance of this class, internally it will create instance of Test class [as you have defined it as instance level variable] and because of this it will again create instance of Test class and so on....

So you will have to remove the instance level object creation as follow :-

public class Test {

    public static void main(String[] args) {
        Test t  = new Test();
    }
}