Tutorial Java – #8 Understand Stack and Heap

In order to have a deep understanding of the Object Oriented Programming in Java or any other OOP language (like C#) you must know how things are managed internally by the Java process and by the JVM. Of course Java syntax and Java implementations of OOP principles are important but you will have a more clear image about the application resources, memory, performance, argument passing, threads and garbage collection if you put questions beyond How I do that ? or How I write that ?. The real questions should be How or Why it is happening like this ? (of course, at some point you should stop and move forward).

In this post I will describe how the application variables are managed, regarding where they are stored (Stack or Heap) and for how long.

Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents

What is the Stack and the Heap

Keeping things simpler (if you know some assembler background you will see that this is a superficial approach) your application is processing data by storing it into memory areas in Random Access Memory. These areas are called:

Stack:

  • a memory space reserved for your process by the OS;
  • the stack size is fixed and it is determined in the compiler phase based on variables declaration and other compiler options;
  • it is important to establish that the stack is limited and its size is fixed (one the process has started, it can’t change the stack size);
  • most of the time, the stack it is used to store functions/methods variables (input arguments and local variables).
  • each method has its own stack (a zone in the process stack), including  main, which is also a function.
  • a method stack exists only during the lifetime of that method: from the calling moment until the return moment;

Heap:

  • a memory space managed by the OS and used by processes to get additional space at run-time;
  • this area it is a global, meaning that any process can use it (of course, processes can’t read or write in another process Heap reserved area);
  • the role of this memory is to provide additional memory resources to processes that need that supplementary space at run-time (for example, you have a simple Java application that is constructing an array with values from console);
  • the space needed at run-time by a process is determined by functions like new (remember, it the same function used to create objects in Java) which are used to get additional space in Heap.

What is stored in Stack and in Heap

Based on previous rules, let’s analyze this simple Java application:

class Student{
    int age;               //instance variable
    String name;     //instance variable
 
    public Student()
    {
        this.age = 0;
        name = "Anonymous";
    }
    public Student(int Age, String Name)
    {
        this.age = Age;
        setName(Name);
    }
    public void setName(String Name)
    {
        this.name = Name;
    }
}
 
public class Main{
	public static void main(String[] args) {
            Student s;                   //local variable - reference
            s = new Student(23,"Jonh");
            int noStudents = 1;          //local variable
	}
}

In order to determine the minimum space (because we focus only on the important elements and we keep things as simple as possible) let’s analyze the Stack requirements. In the next paragraph I describe each method stack separately but in the end all these are placed on the same stack, the application stack.

We start with the main method because for a Java process everything begins and ends with main. Themain local variables, or variables stored on its Stack are:

  • the args reference (it is an array of Strings);
  • the Student reference, named  s;
  • the integer (4 bytes) value, named  noStudents;

The default constructor local variables are:

  • the current created object reference, named  this;
  • that’s all ( remember:  the object and its values are stored in Heap).

The second constructor, the one with arguments, local variables:

  • the reference of the current created object, named  this;
  • the input argument, Age, an integer value
  • the input argument, Name, a String reference

The setName method local variables are:

  • the calling object reference, named this; ( remember:  each non-static class method it is called by an object and that object reference is passed to the method as this)
  • the input argument, Name, a String reference

As I said earlier, all these methods stacks are in fact, parts of a single applications stack. Each part exists during the function lifetime. If you analyze the order in which these methods are called you can define a bigger picture – the process call stack.

For the previous example, when the constructor with arguments it is executed, the call stack looks like this:

Call Stack Example

Call Stack Example

As you can see, from the previous image, the call stack is generated by all the active methods. Because the main method is the process entry point, it is the first method on the call stack. After this moment, each time a method is called, it will be placed on the call stack.

For the previous example, the call stack has the maximum size when it is called the setName method from the Student constructor.

In Heap there are stored all the values that are created using new operator, meaning mostly object values. So, for the previous example, the references are stored on the method stack and the objects are stored in Heap:

Stack & Heap values for the Call Stack example

Stack & Heap values for the Call Stack example

In the previous image, there are described the methods local variables, which are stored on their stack. Also, you can see that objects values (the Student and the String) are stored in Heap.

The Heap values are created by:

  • the Student memory area in Heap is created by calling the new operator and the class constructor;
  • the String value is created during the object initialization inside the class constructor.

What is the lifetime of variables from Stack and Heap

The general rule regarding the lifetime of variables is that they exist at least for the time you need them.

For stack variables, because they are on the method stack, they exist as long as the method is executed. Because main method is a special method (the process starts and ends with main) its local variables exist for the entire execution of the process. For other methods, their stack exists only from the moment we call the method until it ends (with a return or because of an exception).

The values in Heap (object values) exist as long as we have a reference that has the address of that memory area in Heap. If the Heap memory area can’t be reached through a reference (the reference does’t exist or it has another value/address), the Garbage Collector will release that space. (more on Garbage Collector in next tutorial).

Other types of variables, like the class static attributes, are managed in the same way,with the difference that they are stored on the process stack, before using that stack for methods stacks.

Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我! 基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip基于Django+python编写开发的毕业生就业管理系统支持学生教师角色+db数据库(毕业设计新项目).zip
毕设新项目基于python3.7+django+sqlite开发的学生就业管理系统源码+使用说明(含vue前端源码).zip 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我! 学生就业管理系统(前端) ## 项目开发环境 - IDE: vscode - node版本: v12.14.1 - npm版本: 6.13.4 - vue版本: @vue/cli 4.1.2 - 操作系统: UOS 20 ## 1.进入项目目录安装依赖 ``` npm install ``` ## 2.命令行执行进入UI界面进行项目管理 ``` vue ui ``` ## 3.编译发布包(请注意编译后存储路径) #### PS:需要将编译后的包复制到后端项目的根目录下并命名为'static' 学生就业管理系统(后端) ## 1.项目开发环境 - IDE: vscode - Django版本: 3.0.3 - Python版本: python3.7.3 - 数据库 : sqlite3(测试专用) - 操作系统 : UOS 20 ## 2.csdn下载本项目并生成/安装依赖 ``` pip freeze > requirements.txt pip install -r requirements.txt ``` ## 3.项目MySQL数据库链接错误 [点击查看解决方法](https://www.cnblogs.com/izbw/p/11279237.html)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值