What are the differences between local variables and member variables in Java
1. The location of the definition is different < focus >***
Local variables: Inside the method
Member variables: Outside of the method, written directly in the class
2. Different Scope < focus >***
Local variables: Only methods can be used, out of the way to no longer use
Member variables: The entire class can be generalized.
3. Default values are different < focus >***
Local variables: There is no default value, and if you want to use it, you must manually assign the value
Member variables: If there are no assignments, there will be default values, as are the rules and arrays
4. The memory location is different (learn)
Local variables: in stack memory
Member variable, which is located in heap memory.
5. Life cycle is different (learn)
Local variables: As the method is in the stack, it dies as the method stacks.
Member variables: As objects are created, they disappear as objects are garbage collected.
Publiccalss demo01variabledifference{String name;//member Variables Public voidMethodA () {intnum=20;//local variable default value is nullSystem.out.println (num); SYSTEM.OUT.PRINTLN (name); } Public voidMethodB (intparam) { //the parameter of the method is the local variableSystem.out.println (param);//parameter is also a local variable, why not assign a value can be output? //because parameters are bound to be assigned when the method is called. Do not pass parameters will be error. intAge ; //System.out.println (age);//An unassigned value cannot be used and must be assigned//System.out.println (num);//wrong wordingSYSTEM.OUT.PRINTLN (name); }}
What are the differences between local variables and member variables in Java