StackOverFlowError in Java code

161 Views Asked by At

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

    }
}
3

There are 3 best solutions below

2
On BEST ANSWER
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.

4
On

By doing Tmp4 t = new Tmp4 (); you are trying to initialize the object of the same class within it's object which is going in infinite recursion and giving you StackOverflow Exception.

Remove this line as shown below:

public class Tmp4 {
    /* Remove this line */
    Tmp4 t = new Tmp4 ();

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

StackOverFlowError happens when you have an infinite loop in your code just like you have it in line 2.

public class Tmp4 {
Tmp4 t = new Tmp4 (); // This creates an infinite loop
}

That line 2 is called instance initializer and it happens even before the constructor. Now, since you are creating another instance of Tmp4, it will then call it's own instance initializers which will call theirs and so on. The loop will never end.