Where methods live? Stack or in Heap?

前端 未结 6 434
攒了一身酷
攒了一身酷 2020-12-14 13:16

I know that local variables and paramters of methods live in stack, but I not able to figure out where does actually methods live in case of Java?

If I declare any T

6条回答
  •  难免孤独
    2020-12-14 14:07

    The stack is comprised of method invocations. What java pushes onto the stack is a method invocation record, which encapsulates all the variables (both parameters and locally instantiated variables) for that method. When you start a Java application, the main method (which automatically includes the args parameter) is the only thing on the stack:

    main(args)
    

    When say you create a Foo object and call foo.method(), the stack now looks like:

    method()
    main(args)
    

    As methods get called, they are pushed onto the stack, and as they return, they are removed or "popped" from the stack. As variables are declared and used the stack entry, which corresponds to the current method (at the top of the stack), grows to include the size of the variable.

    For your example with threads, each thread will have its own stack which exists independent of each other thread's stack.

提交回复
热议问题