简体   繁体   中英

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)

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

在此处输入图像描述

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

The class Test has a member of type Test, so a new object Test is created, which repeats until the stack is full.

The stack is the place where the JVM (Java Virtual Machine) keeps references to the created objects, which themselves are placed on the heap. Therefore, each time an one Test object gets created, the stack becomes a little larger, until the JVM tells you that it can't put any new object references onto it, creating this exception.

A good explanation for the Java memory allocation can be found here .

Whenever you initialize an instance of Test , its member t is also initialized. But this member is a Test itself, so it initializes its own member t , and so on, until the stack is overflown. The easiest solution would be to remove this member, as it doesn't seem to be used anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM