经典文章: stack 和 heap

来源:互联网 发布:w3cschool php 手册 编辑:程序博客网 时间:2024/05/16 11:15

 http://www.javatutorialhub.com/java-stack-heap.html

 

 

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 clickhere


 

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

 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 郑州住房公积金查询 连云港市住房公积金查询系统 上海住房公积金查询个人账户 滁州住房公积金查询 住房公积金办理条件 住房公积金怎么交 住房公积金密码是什么 赣州住房公积金查询个人账户 南宁市住房公积金中心 昆山住房公积金查询 住房公积金办理 宜宾住房公积金查询 连云港住房公积金查询 柳州住房公积金管理中心 个人住房公积金查询 南宁市住房公积金 住房公积金异地买房 滁州市住房公积金管理中心 住房公积金查询个人账户查询 吉林市住房公积金 洛阳市住房公积金管理中心 河北省住房公积金查询 内蒙古住房公积金管理中心 常州住房公积金管理中心 住房公积金中心 无锡住房公积金管理中心 重庆住房公积金管理中心 吉林省住房公积金 黄石住房公积金查询个人账户 唐山住房公积金管理中心 唐山住房公积金 遵义市住房公积金查询 湖南省住房公积金查询 深圳市住房公积金 保定住房公积金管理中心 阜阳住房公积金查询 临沂住房公积金查询 呼和浩特住房公积金管理中心 住房公积金管理中心网 南京住房公积金查询 邯郸住房公积金查询