Java member variables and local variables initialization and memory operation mechanism

Member variables:

  When the system loads a class or creates an instance of a class, the system automatically allocates memory space for member variables, and automatically assigns initial values ​​to member variables after the memory space is allocated.

 

eyeNum is a class attribute. name is an instance attribute

All person instances accessing eyeNum will access the eyeNum property of the person class. is accessing the same block of memory. If you modify a class property through an instance, it will be changed when all instances are accessed.

 

local variable:

 

After a local variable is defined, it must be explicitly initialized before it can be used. This means that after a local variable is defined, the system does not allocate memory space for the variable. Until the program assigns an initial value to the variable, the system will allocate memory to the local variable and save the initial value to this memory.

  Unlike member variables, a local variable does not belong to any class or instance, so it is always kept in the stack memory of the method in which it resides. If the local variable is a basic type variable, the variable value is directly stored in the stack, and if it is a reference type, the address is stored in the stack.

Variables in stack memory do not need system garbage collection, and variables end with the end of the method or code block. Therefore, the scope of a local variable starts when the variable is initialized and ends until the method or block of code is completed. Because local variables only hold values ​​of primitive types or references to objects, local variables usually take up less memory.

 

When we define a member variable, the member variable will be placed in the heap memory, and the scope of the member variable will be expanded to the scope of the existence of the class or the scope of the object. This range expansion has two disadvantages:

1. Increasing the lifetime of the variable will lead to greater system overhead

2. Expand the scope, which is not conducive to the cohesion of the program.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325724503&siteId=291194637