Search code examples
javainstancestack-overflowheap-memorylocal-variables

What would happen if an object is created in non-static method of class in java?


class Data {
    int x = 20; // instance variable

    public void show() // non-static method
    {
        Data d1 = new Data(); // object of same class Data
        int x = 10;
        System.out.println(x); // local x
        System.out.println(d1.x);// instance variable x
    }

    public static void main(String... args) {
        Data d = new Data();
        d.show(); // "10 20"
    }
}

So my question when an object is created in show() namely 'd1' , it must have its own set of data members and must have allocated a new stack for its show() method , which in return should create a new object and thus the cycle should go on and stack-overflow occurs?? But this is working perfectly fine??


Solution

  • Data d1=new Data(); 
    

    this statement itself will not allocate a new stack for show(). show()'s stack is allocated only when it gets called, for example, when it gets called in main.