Static and final Variables

Source: Internet
Author: User
Tags constant definition
1. static variable

Class member variables can be classified by static or not. One is static modified variables, such as static variables or class variables; the other is a variable that is not modified by static, called an instance variable. The difference between the two is:
For static variables that only have one copy (memory saving) in the memory, JVM only allocates the memory for the static one time, and completes the memory allocation of the static variables during the loading process, you can directly access the available class name (convenient). Of course, you can also access it through an object (but this is not recommended ). For instance variables, each time an instance is created, memory is allocated for the instance variables. The instance variables can be copied multiple times in the memory without affecting each other (flexible ).

2. Final variable:

When you define a variable in a class and add the final keyword before it, it means that once the variable is initialized, it cannot be changed.For the basic type, its value is unchangeable, and for the object variable, its reference cannot be changed.. It can be initialized in two places. One is its definition, that is, it is assigned a value directly when the final variable is defined,The second is in the constructor. You can only choose one of these two places, either give a value at the time of definition, or give a value in the constructor, not both at the time of definition, in the constructor, another value is given.

When the function parameter is of the final type, you can read and use this parameter, but you cannot change the value of this parameter.

In addition, when the internal class in the method uses the parameter variable in the method, this parameter must be declared as final before it can be used.

3. Static final int is generally used for constant definition.

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.