Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Overflow java

Tags:

java

static

Object as a class variable causes the stackoverflow

public class stack {
        stack obj = new stack();   // its obvious that during class loading obj will call class to
        // load and infinite loop will occur. 
}

Lets say i am using static in from class obj

public class stack {
      static stack obj = new stack();  // it will not cause infinite loop and program will //execute successfully
}

Static variables are allocated in to the memory when the class is caught by JVM first time (As far I know). Say during first time only if the JVM starts allocating the memory to the above static object variable. It will intern call the class again and this should also cause infinite loop . Somewhere i am wrong. Can somebody highlight where i am wrong.

like image 899
Aslam anwer Avatar asked Aug 24 '26 23:08

Aslam anwer


1 Answers

No, declaring it as static won't cause an infinite loop. Here is why.

Static variables are initialized during the class loading time. So when your class loads for the first time, compiler will create an instance for the static variable, and that's it. This won't cause your class to load a second time. Since your class is not loading again, this process won't be repeated.

If you declare it as a non-static attribute, then it's a totally different story. Consider this -

public class stack {
    stack obj = new stack();

    ........
}

This declaration is equivalent to -

public class stack {
   stack obj;

    public stack() {
        obj = new stack();    // implicitly moved here by the compiler
    }

    ........
}

From the last example, it's pretty obvious why there is an infinite recursion here. You are creating an instance of the stack class inside its own constructor, which in turn creates another, and then another,......and it goes on, resulting in a Stack Overflow.

like image 184
MD Sayem Ahmed Avatar answered Aug 27 '26 13:08

MD Sayem Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!