Local variables, member variables and static variables in Java

Static variable, also known as class variable


One, the difference

1. Define the location

Local variable: inside the method
Instance variable: inside the class, outside the method
Static variable: inside the class, outside the method

2. Scope

Local variables: valid in methods.
Instance variables: available in the entire class.
Static variables: available in the entire class and can be called directly by the class

3. Default value

Local variable: no default value, need to be assigned before use
Instance variable: have default value
Static variable: have default value

4. Memory location

Local variables: in the stack memory
Instance variables: in the heap memory
Static variables: in the method area

5. Life cycle

Local variables: the same as the life cycle of the method.
Instance variables: take effect when the object of the class is created, and become invalid after garbage collection.
Static variables: exist as the class is loaded, and disappear as the class disappears

Two, summary of the use of variables

public class Test{
    
    
	int a;//实例变量,有默认值
	public void method(int b;/*局部变量*/){
    
    
		int c;//局部变量,无默认值
		System.out.println(c);
		//如果打印直接打印变量 c 程序编译会出错,必须进行赋值
		System.out.println(b);
		//如果打印直接打印变量 b 程序编译不会出错
		//虽然 b 没有进行赋值,但是在方法调用时,必然会给方法传递参数,b 也就被赋值了
	}
}

In the process of code writing, the scope of the variable should be minimized. The shorter the variable is in the memory, the higher the performance.

public class Test {
    
    
    static int a;//静态变量
}
class Test1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Test.a);//静态变量在其它类中直接用类名.变量名
    }
}

Guess you like

Origin blog.csdn.net/weixin_44580492/article/details/105737751