Search code examples
javaoopstack-overflow

Getting exception in thread "main" java.lang.StackOverflowError


I am new to Java and OOPs and here is my issue. When I run the below code, I get the

Exception in thread "main" java.lang.StackOverflowError.

The problem is in the code were I create an object of JavaApplication1.The problem is not occurring for class App2. The code works fine if the object ja is created inside the run method. Can you explain me why?

package javaapplication1;

public class JavaApplication1 {

    int i, k, j;

    class App2 {
        int i = 23;
        int j = 12;
    }

    App2 a2 = new App2();
    JavaApplication1 ja = new JavaApplication1();

    public void run() {
        ja.i = 10;
        a2.i = 26;
        a2.j = 18;
        System.out.println(i + "," + j + "'" + ja.i + "'"
                           + a2.i + "'" + a2.j + "'" + k);
    }

    public static void main(String[] args) {
        int k = 24;
        JavaApplication1 ja1 = new JavaApplication1();
        ja1.run();
        ja1.i = 18;
        System.out.println(ja1.i + "'" + "'" + k);
    }
}

Solution

  • Your class JavaApplication1 has field JavaApplication1 ja which holds another instance of JavaApplication1 class, which also has its own ja field which holds another instance of JavaApplication1, and so on and on.

    In other words, when you create instance of JavaApplication1 this instance creates its inner instance of JavaApplication1 and this inner instance creates another JavaApplication1 instance, which again creates instance JavaApplication1... until stack will be full.

    So when you run this code in your main method

    JavaApplication1 ja1 = new JavaApplication1();
    

    something like this happens

           +-----------------------------------------------+
    ja1 -> | JavaApplication1 instance                     |
           +-----------------------------------------------+
           |                                               |
           |       +------------------------------------+  |
           | ja -> | JavaApplication1 instance          |  |
           |       +------------------------------------+  |
           |       |                                    |  |
           |       |       +-------------------------+  |  |
           |       | ja -> |JavaApplication1 instance|  |  |
           |       |       +-------------------------|  |  |
           |       |       |                         |  |  |
           |       |       | ja -> ....              |  |  |
           |       |       +-------------------------+  |  |
           |       +------------------------------------+  |
           +-----------------------------------------------+
    

    Anyway I don't see where ja field is ever used, so consider removing it from your code.