In Java, the scope of a variable is divided into four levels: class-level, object-instance-level, method-level, block-level.
Class-level variables, also known as global-level variables or static variables, need to be decorated with the static keyword, which you can learn from in contrast to static variables in C + +. Class-level variables already exist after the class is defined, occupy memory space, can be accessed through the class name, and do not need to be instantiated.
An object instance-level variable is a member variable that is not allocated until the memory space is instantiated for access.
A method-level variable is a variable defined inside a method, which is a local variable.
A block-level variable is a variable that is defined inside a block, the lifetime of the variable is the block, and the block disappears, such as the IF and for statements. A block is a code surrounded by curly braces, for example:
- {
- int Age = 3;
- String Name = "Www.weixueyuan.net";
- //correct, the age and name variables can be accessed inside the block
- System. Out. println(name + "already" + Age + "old");
- }
- Error, the age and name variables cannot be accessed outside the block
- System. Out. println(name + "already" + Age + "old");
Description
- In addition to accessing the method-level variables inside the method, you can access the class-level and instance-level variables.
- The inside of a block can access class-level, instance-level variables, and if the block is contained inside a method, it can also access the method-level variables.
- Method-level and block-level variables must be initialized to be displayed, otherwise they cannot be accessed.
Demo Code:
- Public class Demo{
- public static String name = "Micro School"; //class-level variables
- public int i; //Object instance-level variables
- //attribute block, run when class initializes properties
- {
- int J = 2; Block-level variables
- }
- public void test1() {
- int J = 3; //Method-level variables
- if(j = = 3) {
- int k = 5; //block-level variables
- }
- //Cannot access block-level variables, block-level variables can only be accessed within the block
- System. Out. println("name=" + name + ", i=" + I + ", j=" + j);
- }
- public static void main(String[] args) {
- //Do not create objects, access class-level variables directly from the class name
- System. Out. println(Demo. Name);
- //How to create an object and access it
- Demo T = New demo();
- T. Test1();
- }
- }
Operation Result:
Micro Science Court
Name= Micro School, I=0, j=3
Scope of the 6.Java variable