On local and global variables in Java

This paper introduces the local variables and global variables in Java as follows:

1. Local variables:

Definition of local variable: all variables defined in the method are local variables (the main method is also a method, so the variables defined in the main method are also local variables).

Survival time: the survival time of the local variable is consistent with that of the method. When the method is called to declare and initialize the local variable, the local variable is created and allocated memory space; Until the method call ends, the local variable ends;

Whether to initialize: local variables must be initialized before use. By default, the system will not initialize local variables. If local variables are not initialized before use, an error will be reported in the compiler; If the local variable is declared and not initialized, but has not been used, the compilation will not report an error; (local variables must be initialized before use)

Creation location: local variables are created in stack memory;

2. Global variables:

2.1 non static global variables:

Definition of non static global variables: all non static global variables are defined in the class. They are member variables or member attributes of the class and belong to a part of the class (or an object);

Lifetime: non static global variables are loaded in heap memory, created with declaration initialization, and die with object extinction;

Initialization required: global variables do not need to be forcibly initialized, and the system will assign values by default according to their data types; However, it is recommended to initialize when declaring;

Create location: it is created in heap memory, because the number of non static global variables, the member variables of the object are part of the object;

2.2 static global variables:

Definition of static global variables: static class member variables;

Lifetime: static global variables are generated when the bytecode file of the class is loaded, and disappear when the bytecode file disappears. The lifetime is longer than that of the class object; Initialize: all global variables can be uninitialized, as can static variables. The system will automatically assign default values according to their data types, but it is recommended that variables be initialized when declared;

Creation location: static variables exist in memory, so static global variables also exist in heap memory.

summary

The above is the full introduction of local variables and global variables in Java. I hope it will be helpful to you.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>