Detailed explanation of variables and constants in Java

variable and constant

There are a lot of data in the program to represent the state of the program. Some data will change in the value during the running process of the program, and some data cannot change in the value during the running process of the program. These data are called variables and constants in the program respectively.

In the actual program, you can choose whether to use variable representation or constant representation according to whether the data changes during the program operation.

variable

Variables represent the state of the program. The program changes the state of the whole program by changing the value of variables, or larger, that is, to realize the functional logic of the program.

In order to easily reference the value of a variable, you need to set a name for the variable in the program, which is the variable name. For example, in a 2D game program, if you need to represent the position of the character, you need two variables, one is the X coordinate and the other is the Y coordinate. The values of these two variables will change during the running of the program.

Because Java language is a strongly typed language, variables must be declared before use. The syntax format of declaring variables in the program is as follows:

Data type variable name;

For example: intx;

In this syntax format, the data type can be any type in the Java language, including the basic data type introduced earlier and the composite data type to be introduced later. The variable name is the identifier of the variable, which needs to comply with the naming rules of the identifier. In practical use, the name generally corresponds to the purpose of the variable, so as to facilitate the reading of the program. Spaces are used between data types and variable names. There is no limit to the number of spaces, but at least one is required. Statement uses'; ' As an end.

You can also set the value of a variable while declaring it. The syntax format is as follows:

Data type variable name = value;

For example: intx = 10;

In this syntax format, the previous syntax is consistent with the content described above. The subsequent "=" represents assignment, in which "value" represents specific data. Note that the difference "= =" represents whether to judge equality. In this syntax format, the value type is required to be consistent with the data type of the declared variable.

In the program, the value of the variable represents the state of the program. In the program, the value stored in the variable can be referenced by the variable name, or the variable can be re assigned. For example:

intn=5;

n=10;

In the actual development process, what type of variables need to be declared, how many variables need to be declared, and what values need to be assigned to variables are all determined according to the program logic. What is listed here is only the expression format.

constant

Constants represent values that cannot be changed during program operation.

Constants have two main functions during program operation:

1. Represents a constant to facilitate program modification (for example, the value of PI)

2. Enhance the readability of the program (for example, the constants up, down, left and right represent up, down, left and right, and their values are 1, 2, 3 and 4 respectively)

For the constant syntax format and variable type, you only need to add the keyword final in front of the variable syntax format. In the Java coding specification, constant names are required to be capitalized.

The syntax format of the constant is as follows:

Final data type constant name = value;

Final data type constant name 1 = value 1, constant name 2 = value 2,... Constant name n = value n;

For example:

finaldoublePI=3.14;

finalcharMALE=‘M',FEMALE=‘F';

In Java syntax, constants can also be declared first and then assigned, but they can only be assigned once. The example code is as follows:

finalintUP;

UP=1;

Detailed explanation about final

Final is used to declare attributes (constants), methods and classes. It means that once the attribute is allocated memory space, it must be initialized (there will be no default initialization, and so will local variables. The default initialization only has ordinary non final member attributes, for static (no final modification) class variables are initialized by default during class connection. For example, privateinta; when class instantiation, the initial constructor is 0 by default. In short, variables must be initialized before they can be used, which is one of the security of Java. The meaning of the keyword final is "this cannot be changed" or "final";

So why stop change?

The inventor of the Java language may have prevented change for two purposes:

1). Efficiency issues:

Some methods of some classes in JDK are not allowed to be covered by users. Designers may think that the methods used are already the best methods. Users covering privately or inadvertently will affect the function of the JVM or the system;

2). Required for design:

As we all know, in some cases, the final keyword must be used, such as parameter passing of anonymous inner classes in methods

Modify variable:

The final member variable represents a constant and can only be assigned once. The value will not change after assignment.

[modification method]:

Final methods cannot be overridden by subclass methods, but can be inherited.

[decoration type]:

The final class cannot be inherited and has no subclasses. All methods in the final class are final. (such as string class)

1. The attribute variables of a class modified by final but not static can only be initialized in two cases: (must be initialized)

a. Assign values when it is declared

b. Initialize in constructor

Explanation: when this attribute is modified to final instead of static, It belongs to the resource of the instance object of the class (instance constant). When the class is loaded into memory, this attribute does not allocate memory space to it, but only defines a variable A. this attribute is allocated memory space only when the class is instantiated, and the constructor is executed at the same time. Therefore, the attribute is initialized, which is consistent with the need to initialize when it is allocated memory space to Conditions that will not change after

2. The attribute variable of a class modified by static but not modified by final can only be initialized in two cases: (it can not be initialized)

a. Assign values when it is declared

b. Initialize in static or non static cache

Explanation:

When the properties of a class are modified to static at the same time, He belongs to a class of resources (class variable). After the class is loaded and connected, there are three steps: first verify; then prepare. When preparing, allocate memory first, and then initialize by default; you can parse. Finally, initialize the class. Before class initialization, you must ensure that its parent class has been initialized, so the superclass is initialized first. For the interface, you do not need to initialize its parent interface When initializing, it puts the class variable initialization statement and static initialization statement into the class initialization method. Therefore, if there are no such two statements, there will be no < clinit > class initialization method, and the constructor will be executed when the class is instantiated. Therefore, with the constructor, this property is not initialized at this time The program will report an error The static block is executed only once when the class is loaded, so it can be initialized in the static block

3. Attribute variables of classes modified by both final and static can only be initialized in two cases: (must be initialized)

a. When it is defined

b. Initialize in a static block of a class

c. Pay attention to calling the constructor that throws an exception during initialization, especially when implementing the singleton mode (this is the only way to initialize)

For example:

Explanation:

When the attribute of a class is modified as static and final at the same time, it belongs to the resource of the class (class constant), so the class must have allocated memory for this attribute when it is loaded into memory (that is, when the application starts), so the attribute already exists and it is modified by final, so its initialization value must be given after the attribute is defined The constructor is executed only when the class is instantiated, so it can be initialized in the static block

Final variable = = constant in Java

[change and invariance of final variable]: final indicates that the value or reference of the variable is unchanged

Some people say that the final variable is immutable after assignment. This variable can be basic data type + string or object

So what exactly does this invariance mean?

This invariance refers to the reference, the address, and the content of the referenced object is still variable. Note: if it is an object, pay attention to the class initialization conditions at this time

That is, the final variable always points to an object, which is a constant pointer, not a pointer to a constant.

[specific application of final keyword]:

[final + variable]:

In practical application, this form is very rare.

For example, the logger is OK, but it doesn't seem to be very practical. Maybe the user still wants to change the logger variable through the setter.

[static + final + variable]:

Constant. Often used.

[final + method]:

JDK is commonly used, but it is not commonly used.

[final + class]:

The helper class is often used.

[final for parameter passing of anonymous inner class]:

It is often used in multithreaded testing.

[final parameters for method]:

Not often.

Extension:

All variables in the interface are public static final. So you can write:

publicstaticfinalinti=10;

Or

inti=10; (part can be omitted)

Note that the initial value should be given to the variable when declaring

Explanation:

First, you should understand the meaning of the interface Interface is to provide a unified 'protocol', and the attributes in the interface also belong to the members of the 'protocol' They are public, static, and final constants Equivalent to a global constant

Abstract classes are incomplete classes, which are equivalent to an intermediate layer between interfaces and concrete classes That is, it meets the abstraction of the interface and the specific implementation

If the interface can define variables, but the methods in the interface are abstract, the properties cannot be modified through behavior in the interface. Some people will say that it doesn't matter. You can modify the properties in the interface through the behavior of the object implementing the interface. This is certainly no problem, but consider this situation. If interface a has a static variable a with public access rights. According to the semantics of Java, we can access variable a without implementing the object of the interface through A.A = XXX; You can change the value of variable a in the interface. Just as this can be done in an abstract class, all objects implementing interface a will automatically have the changed value of a, that is, if a is changed in one place, the value of a in all these objects will also change. If you can modify the value: what is the difference between this and the abstract class? How do you reflect the higher abstraction level of the interface, how do you reflect the unified protocol provided by the interface, and what do you need to do with this abstraction of the interface? Therefore, variables cannot appear in the interface. If there are variables, it conflicts with the unified abstraction provided by the interface. Therefore, the attributes in the interface must be constants, which can only be read and cannot be changed, so as to provide a unified attribute for the object implementing the interface.

Generally speaking, what you think is going to change is put in your own implementation, not in the interface. The interface is just a higher-level abstraction of the attributes and behaviors of a class of things. It is closed to modifications and open to extensions (different implementations). The interface is an embodiment of the opening and closing principle.

summary

The above is all about the detailed explanation of variables and constants in Java in this article. I hope it will be helpful to you. Interested friends can continue to refer to this site: detailed explanation of semaphore counting semaphore in Java Concurrent Programming, detailed explanation of mutex semaphore and multithread waiting mechanism in Java, brief discussion on local variables and global variables in Java, etc. welcome to put forward your valuable opinions, and the editor will reply in time. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>