Java Basics-member variables and local variables

Source: Internet
Author: User

I. Local variables

In Java, a variable defined in a class is called a member variable, and its scope is valid within the method. When a local variable is used, it must be initialized before it can be used, or it cannot be compiled. The following code local variables are not initialized, prompting an error:

    

Two. member variables

1. A variable defined in a method is a local variable whose scope is valid throughout the class. When you use member variables, you do not need to initialize variables, and the system can initialize by default. The initialization principle is the following table:

    

Without initialization, the code is as follows:

      

Note that a final decorated member variable must be initialized first:

      

2. If the local variables and member variables defined in a method have the same name, this is allowed when the method accesses a local variable through a variable name instead of a member variable.

      

The printed statement in the above code outputs 20, not 10.

Java Basics-member variables and local variables

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.