×

Discussion Board

Results 1 to 3 of 3

Thread: StackOverFlow

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    91

    StackOverFlow

    Hi Guys,
    Below there is a pseudocode cause StackOverFlow error. Why?

    public class StackOverFlowDemo{


    public static void main(String[] str){

    Stack stack = new Stack();
    }
    }


    class Stack{

    Stack stack = new Stack();
    }

    If you make a little change in class Stack like:

    static Stack stack = new Stack();

    The error has been solved. What we have to do is only add static. Why ?


    Can anyone explain me about this scenario.



    Regards,
    Amit Yadav

  2. #2
    Super Contributor
    Join Date
    Jan 2008
    Location
    Amravati, India
    Posts
    546

    Re: StackOverFlow

    Case 1:
    Code:
    public class StackOverFlowDemo{
    
    
    public static void main(String[] str){
    
    Stack stack = new Stack(); //Line No. 1
    }
    }
    
    class Stack{
    
    Stack stack = new Stack(); //Line No. 2
    }
    When you make a new object of class Stack in Line No. 1, java virtual machine will allocate some memory for this object and initialize all the variables.
    While doing this, it will initialize variable "stack" and Line No. 2 says how to initialize variable "stack". So java virtual machine will create a new object of class Stack and initialize all variables of it.
    While doing this, it will initialize variable "stack" and Line No. 2 says how to initialize variable "stack". So java virtual machine will create a new object of class Stack and initialize all variables of it.
    While doing this, it will initialize variable "stack" and Line No. 2 says how to initialize variable "stack". So java virtual machine will create a new object of class Stack and initialize all variables of it.
    and so on...
    So, stack overflow !!!

    Case 2:
    Code:
    public class StackOverFlowDemo{
    
    
    public static void main(String[] str){
    
    Stack stack = new Stack(); //Line No. 1
    }
    }
    
    class Stack{
    
    static Stack stack = new Stack(); //Line No. 2
    }
    Since variable "stack" is declared static at Line No. 2, exactly one copy of it will be present in the memory which will be initialized at program start-up.
    When you make a new object of class Stack in Line No. 1, java virtual machine will allocate some memory for this object and initialize all the variables.
    But there are no variables present in the class Stack. So nothing to do.
    So, no stack overflow...

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    91

    Re: StackOverFlow

    Hello Arpit,

    This time you really gave a tremendous answer, my anxiety is no more left. Thanks a lot!


    Regards,

    Amit Yadav

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×