Search code examples
javastack-overflow

Getting java.lang.StackOverflowError


I am getting a Stackoverflow exception for a simple java code. I am not quite sure why its coming. Could someone please take a look and let me know what wrong.

Thanks in advance.

 public class Test1 {
    public Test1(int val) {
        System.out.println(val);
    }
}

public class Test {
    Test t = new Test(10);
    public Test(int n) {
        new Test1(n);
    }

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

I am getting below Exception.

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

Solution

  • Please Find Screenshot in which, this line initalting this class, and then again, this line executing and repeating same process over and over again..

    enter image description here

    So solution is to do this by following way :

    public class Test1 {
        public Test1(int val) {
            System.out.println(val);
        }
    }
    
    public class Test {
        int n = 10; // this will initiate this number by 10
        public Test(int n) {
            new Test1(n);
        }
    
        public static void main(String[] args) {
            new Test(5);
        }
    }