Go Java Variables and constants

Source: Internet
Author: User
Tags modifier naming convention value of pi

Variables and constants

In the program there is a large amount of data to represent the state of the program, some of the data in the course of the program's operation, the value will change, some data in the program during the operation of the value can not be changed, the data in the program is called variables and constants.

In the actual program, you can choose whether to use a variable representation or a constant, depending on if the data has changed in the program's operation.


Variable

The variable represents the state of the program. The program changes the value of the variable to change the state of the whole program, or more, that is, the implementation of the program's functional logic.
In order to conveniently reference the value of a variable, you need to set a name for the variable in your program, which is the variable name. For example in 2D game program, need to represent the position of the person, then need 2 variables, one is x coordinate, one is the y coordinate, the value of these two variables will change during the program running.
Because the Java language is a strongly typed language, variables must first be declared before they are used, and the syntax for declaring variables in a program is as follows:
Data type variable name;
For example: int x;
In this syntax format, the data type can be any type in the Java language, including the basic data types described earlier and the composite data types that will be described later. The variable name is the identifier of the variable and requires a naming convention that conforms to the identifier, which, in practice, corresponds to the purpose of the variable so that it is easy for the program to read. The data type and variable names are separated by spaces, with no limit on the number of spaces, but at least 1 are required. The statement uses ";" as the end.
You can also set the value of the variable while declaring it, with the syntax in the following format:
Data type variable name = value;
For example: int x = 10;
In this syntax format, the preceding syntax is consistent with what is described above, and subsequent "=" represents the assignment, where the "value" represents the specific data, and the difference between "= =" represents the equality of the judgment. In this syntax format, the type of the required value needs to be the same as the data type that declares the variable.
In the program, the value of the variable represents the state of the program, and the value stored in the variable can be referenced by the variable name in the program, or the variable can be re-assigned. For example:
int n = 5;
n = 10;
In the actual development process, you need to declare what type of variable, how many variables need to be declared, what values need to be assigned to the variable, all according to the logic of the program, the list is only the format of the expression.


Constant

Constants represent values that cannot be changed while the program is running.
Constants have 2 main functions in the process of running a program:
1. Representative constant, easy to modify the program (for example: the value of pi)
2. Enhance the readability of the program (for example: constant up, down, left, and right-resolved representatives up and down, with values of 1, 2, 3, and 4, respectively)
The syntax format and variable type of a constant, just precede the syntax format of the variable to add the keyword final. In the Java encoding specification, the constant name must be capitalized.
The syntax format for constants 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:
Final double PI = 3.14;
Final char male= ' M ', female= ' F ';
In Java syntax, constants can also be declared first, then assigned, but only once, and the sample code is as follows:
final int up;
up = 1;

about final details
     final for declaring properties (constants), methods, and classes, Indicates that the property must be initialized once allocated memory space (there will be no default initialization, the local variable is the same, the default initialization is only a normal non-final member property, for the static (no final decoration) class variable, class connection time has default initialization, for like private int A; When a class is instantiated, the constructor defaults to 0, in short, the variable must be initialized before it is available, which is one of Java's security.                      Final The meaning of this keyword is "This cannot be changed" or "final state";
    so why stop the change? The inventor of the
    Java language may block changes for two purposes:
    1). Efficiency issues:
    Some of the methods of some classes in the JDK are not allowed to be overwritten by the user, the designer may think that the method used is the best method, the user privately covered, or inadvertently overwritten, will affect the JVM or the system's performance;
    2). Design Required:
    It is well known that some cases must use the final keyword, such as the parameter passing of an anonymous inner class in a method

"Modifier variable":
The final member variable represents a constant, which can only be assigned once, and the value will no longer change after the value is assigned.
"Modification Method":
The final method cannot be overridden by a class method, but can be inherited.
"Modifier class":
The final class cannot be inherited, there are no subclasses, and all methods in the final class are final. (such as the String Class)


1.be final modified without being modified by staticThe property variables of a class can only be initialized in two cases: (must be initialized)
A. Assigning values at the time it is declared
B. Initialize in constructor
Explanation:                                                                                                                                                                                               When this property is modified to final, not static, it belongs to the resource of the instance object of the class (instance constant), when the class is loaded into memory, this property does not allocate memory space, but only defines a variable a, only when the class is instantiated, this property is allocated memory space, When instantiated, the constructor is executed at the same time, so the property is initialized, and it conforms to the condition that it needs to be initialized when it is allocated memory space and will not change later.

2. Property variables of a class that are static modified and not final modified can only be initialized in two cases: (Can not be initialized)
A. Assigning values at the time it is declared
B. Initializing in static or non-static fast
Explain:
When the property of a class is modified to be static at the same time, he belongs to the resource of the class (class variable), after the class is loaded, the connection is divided into three steps: first verify; then prepare, allocate memory first, then initialize by default, and parse. Finally, class initialization, before class initialization, must ensure that its parent class has been initialized, so the first to initialize the superclass, for the interface, do not have to initialize its parent interface. Class initialization, it puts the class variable initialization statements and static initialization statements into the class initialization method, so if there is no such statement, there is no <clinit> class initialization method, and the constructor is executed when the class is instantiated, so with the constructor, This property is not initialized at this time. The program will error. The static block is executed when the class is loaded and is executed only once, so it can be initialized in the static block.

3. Property variables for classes that are both final and static modified can be initialized in only two cases: (must be initialized)
A. At the time it is defined
B. Initialize in static block of class
C. In particular, when initializing a constructor that throws an exception, it is initially noted, especially when implementing a singleton pattern (which can only be initialized)
Such as:
Class A
{
private final static A;
Static
{
Try
{
A=new A ();
}catch (Exception e)
{
Throws new RuntimeException (e); Must have, otherwise the correct initialization of the constants cannot be completed
}
}
Private A () throws exception{}
}
Explain:
When the property of a class is modified to both static and final, he belongs to the resource of the class (class constant), then the class is loaded into memory (that is, when the application starts) it is already allocated memory for this property, so the property already exists, and it is final decorated, Therefore, the value must be initialized after the property has been defined. The constructor is executed when the class is instantiated, so this property is not initialized when the constructor is used. The static block is an error when the class is loaded and executes only this time, so the The static block can be initialized.

Final variable = = constant in Java

Final variable is immutable: final indicates that the value or reference of the variable is constant
    some say that the final variable is immutable after the assignment, which can be a basic data type +string or an object
     So what does this constant mean?
    This invariant refers to the reference, which is the address, and the contents of the referenced object are still mutable. Note: If you are an object, notice that the class initializes the condition
    that is, the final variable always points to an object and is a constant pointer, not a pointer to a constant.

"Final keyword specific application":
"Final+ variable":
In practical applications, this form is very rare.
For example, logger is possible, but seemingly not very practical, perhaps the user still wants to change the logger variable by setter.
"Static+final+ variable":
Constant. Often used.
"Final+ Method":
JDK is commonly used, but it is not used by itself.
"Final+ class":
Helper classes are often used.
"Final parameter passing for anonymous internal classes":
Often used in multithreaded testing.
"Final parameter for method":
Not used.

Extended:

The variables inside the interface are public static final. So you can write this:
public static final int i=10;
Dolly Mix
int i=10; (Can omit part)
Notice that the variable is given an initial value at the time of declaration.

Explain:
First you need to understand what the interface means. An interface is a uniform ' protocol ', and the attributes in the interface are members of the ' protocol '. They are public, static, and final constants. Equivalent to a global constant.
An abstract class is a class that is not ' complete ', equivalent to an interface and a middle layer of a concrete class. That is, to satisfy the abstraction of the interface and to satisfy the concrete implementation.
If an interface can define a variable, but the method in the interface is abstract, the property cannot be modified by behavior in the interface. Some people will say, no relationship, you can modify the properties of an interface by implementing the behavior of the interface's objects. This is of course not a problem, but consider such a situation. If interface A has a static variable A that has public access permissions. According to Java semantics, we can change the value of variable A in the interface without accessing the variable A through the object that implements the interface, through a.a = xxx; As can be done in an abstract class, all objects that implement interface A will automatically have the value of the changed a, which means that a place has changed a, and the value of a in all these objects has changed. If you can modify the value: What is the difference between this and the abstract class, how to embody the higher level of abstraction of the interface, how to embody the unified protocol provided by the interface, then what is the interface of this abstraction to do? Therefore, the interface can not appear in the variable, if there are variables, and the interface provided by the unified abstraction of the idea is inconsistent. Therefore, the attribute in the interface must be constant, can only be read and cannot be changed, so as to provide a uniform property for the object that implements the interface.
In layman's words, what you think is to change is put in your own implementation, not in the interface, interface is just a kind of things of the properties and behavior of a higher level of abstraction. For the modification to close, the extension (different implementation implements) Open, interface is a manifestation of the principle of closure.

(Reprint address: https://www.cnblogs.com/langtianya/p/3868135.html)

Go Java Variables and constants

Related Article

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.