A very basic introduction about Java stack and heap

Forwarded from http://www.javatutorialhub.com/wiki/Stack_and_Heap

Stack and Heap

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.


Click to watch video


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.jpg


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值