经典文章: stack 和 heap
发布日期:2021-10-02 09:00:28 浏览次数:5 分类:技术文章

本文共 1854 字,大约阅读时间需要 6 分钟。

 

 

 

The JVM divided the memory into following sections.

 

1)      Heap

2)      Stack

3)      Code

4)       Static

 

This division of memory is required for its effective management.

 

 

The code section contains your bytecode.

 

The Stack section of memory contains methods, local variables and reference variables.

 

The Heap section contains Objects (may also contain reference variables).

 

The Static section contains Static data/methods.

 

Of all of the above 4 sections, you need to understand the allocation of memory in Stack & Heap the most, since it will affect your programming efforts

 

difference between instance variables and local variables

 

Instance variables are declared inside a class but not inside a method

 

  class Student{

    int num; // num is  instance variable

    public void showData{}

Local variables are declared inside a method including method arguments.

 

    public void sum(int a){

       int x = int a +  3;

      // a , x are local variables

   }

 

the following video demonstrates how memory is allocated in stack & heap.

 

Please be patient . Video will load in some time. If you still face issue viewing video click

 

Points to Remember:

  • When a method is called , a frame is created on the top of stack.
  • Once a method has completed execution , flow of control returns to the calling method and its corresponding stack frame is flushed.
  • Local variables are created in the stack
  • Instance variables are created in the heap & are part of the object they belong to.
  • Reference variables are created in the stack.

 

Point to Ponder:

What if Object has a reference as its instance variable?

 

public static void main(String args[]){

   A parent = new A();

   //more code

}

 

 class A{

   B child = new B();

   int e;

  //more code

}

 

 class B{

  int c;

  int d;

  //more code

}

 

In this case , the reference variable “child” will be created in heap ,which in turn will be pointing to its object, something like the diagram shown below.

 

java-stack-heap

 

转载地址:https://blog.csdn.net/jiafu1115/article/details/7086699 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java method invoke的指令简介
下一篇:基本类型到底存哪?

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月22日 13时23分28秒