Difference
1. Location in the class
Member variables: in the class, outside the method
2. Location in the memory
Member variables: Heap
Local variables: Stack
3. Initialized value
Member variables: have default values
Local variables: no default value, only definition and assignment can be used
Life cycle
Member variables: created with the creation of the object, disappear with the disappearance of the object
Local variables: exist with the call of the method and disappear with the end of the method
Instance
The problem of duplicate names of member variables and local variables , proximity principle;
can be distinguished using the this keyword. this.string refers to the member variables in the class, not within the method.
public class Demo{ String string= "成员变量"; public static void main(String[] args) { new Demo().show(); } public void show() { String string= "局部变量"; System.out.println(string); } }
The above is the detailed content of What are the differences between different variables in java. For more information, please follow other related articles on the PHP Chinese website!