What are the differences between local variables and member variables in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.