Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...