The variables in Java are divided into the following three types:
- Local variables
- Member variables
- class variables (static variables)
-
- Local variables are allocated in-memory stack space.
- Local variables do not have default values, so they must be initialized first if they are to be used.
- Local variables are declared in methods, construction methods, and code blocks (code blocks are blocks of code in curly braces, variables declared in curly braces are local variables, and their scope is within the range of curly braces, and local variables are destroyed automatically once the code block statement executes).
- Local variables cannot be modified by the access modifier.
Member variables are also called global variables, which include instance variables, class variables, and constants. But in my understanding, it is generally used to refer to the example variables are mostly, instance variables like the following several characteristics:
-
- Instance variables are declared in a class, but beyond methods and construction methods, the scope is the entire class.
- The instance variable is created when the object is created, destroyed as the object is destroyed, and its memory is allocated in the heap space.
- Instance variables can be declared before they are used, or they can be declared after use.
- Instance variables can be decorated with access modifiers.
- Instance variables have default values, the default value type is 0, the default for Boolean type is false, and the reference type defaults to NULL.
- When instantiating an object, the value of the instance variable is also determined.
A class variable is also called a static variable, often modified with static (my understanding is that the static variable is the variable that is modified with static).
-
- Static variables are created at the beginning of the program and destroyed at the end of the program.
- No matter how many objects a class creates, static variables have only one copy, that is, static variables in different objects are actually pointing to the same one.
- Class variable names are generally recommended to use uppercase when the class variable is declared as public static final type. Other normal naming.
- The default value is the same as the instance variable.
- Static variables can be accessed directly with the class name plus the variable name, which is Classname.var, but the instance variable must be accessed through the instance object.
- Non-static members cannot be accessed in a static method.
Public class test{ public int A; Instance variable public static int B; Static variable public void C () { int D; Local variable }}
Variables in Java