Search code examples
javastack-overflow

StackOverflow exception occuring when running the java class


I have a class Test. When i run the program it throws Stackoverflow error.

Class:

public class Test {

   private Test test = new Test();
    
   public Test() {

      System.out.println("ijshfiksh");
   }



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

Error

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

Can anyone tell my why this is happening?


Solution

  • As you can see from here:

    public class Test {
       private Test test = new Test();
       ...
    }
    

    You are creating an instance of Test inside Test: to build that Test instance, you have to build another instance of Test, which also requires an instance of Test, and so on