Search code examples
javastack-overflowlocal-variablesobject-initialization

StackOverFlowError in Java code


I am writing a simple code and I am receiving an StackOverflowError in following code at line 2: Tmp4 t = new Tmp4 (); I dont get error if I omit line 6 ( initialization of p) or on omiting line 2. Also I am not doing a recursive call.

I want to ask why it is giving a such Error. And on omitting line 2 or line 6 it is not giving StackOverflowError.

Also it gives on my system only or problem with the code.

Thanks.

public class Tmp4 {
    Tmp4 t = new Tmp4 ();

    public static void main(String[] args) {
            System.out.println("main");
            Tmp4 p = new Tmp4 ();
            System.out.println("main2");

    }
}

Solution

  • public class Tmp4 {
        Tmp4 t = new Tmp4 (); //Line 4
    
    public static void main(String[] args) {
        System.out.println("main"); // Line 1
        Tmp4 p = new Tmp4 (); //Line 2
        System.out.println("main2"); //Line 3
    
        }
    }
    

    When you start your program, line1 and 2 are the first executed. line 2 is where you initialise a new object of type Tmp4. With initialisation line 4 gets called which creates again a new object of type Tmp4. With initialisation of t line 4 gets called again resulting in an infinite recursive call, hence the StackOverflowException. Remove line 4 to remove the cause of the StackOverflowException. Because of the infinite loop caused by line 4, line 3 is never executed.