Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)
question from:https://stackoverflow.com/questions/65863076/getting-java-lang-stackoverflowerror

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
616 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...