A constant is an identifier whose value remains constant during operation. and constants can only be referenced in the program and cannot be re-assigned.
below, we define a global constant PI in the math class the name of the variable that is decorated with the final keyword is best capitalized.
Public class Math { // define a global constant pi public staticfinal Double PI = 3.1415926; }
The advantages of constants
If you fill in the numbers directly in the program, the readability of the program becomes worse, and the programmer forgets what the numbers or strings mean, and the user doesn't know where they are from or what they represent. In addition, if the value changes, it will change in many places, both cumbersome and error-prone, the program maintainability enhanced.
naming rules for Java constants
(1) In Java, adding the final keyword to a variable declaration represents a constant, and adding the static keyword represents a class variable. In general, we combine static with final to declare a constant. (2) Try to use the represented meaning intuitive to represent numbers or strings that will appear more than once in a program.
declaring variables in the Java interface
Because variables declared in the Java interface are automatically added to the public static final modifier at compile time. That is, it is automatically declared as a global constant. Thus the Java interface is usually the best place to store constants.
The following two paragraphs are equivalent in code
Public Interface Student { publicstaticfinal String name = "Hamber"; Public Static Final int age =; }
Public Interface Student { = "Hamber"; int age =; }
Hexadecimal integer constants: When in hexadecimal, you need to start with 0x or 0X, such as 0xff,0x9a.
Octal integer constant: octal must start with 0, such as 0123,034.
Long integer: Long integer must end with L, such as 9l,342l.
Floating-point constants: Because the default type of the decimal constant is double, you must add F (f) after the float type. The same variable with decimals defaults to the double type.
such as: float F;
f=1.3f;//must declare F.
Character constants: Literal constants are enclosed in two single quotes (note that string constants are enclosed in two double quotes). The characters in Java account for two bytes. Some of the commonly used escape characters:
①\r means accept keyboard input, equivalent to press ENTER;
②\n indicates a line break;
③\t represents a tab, equivalent to the table key;
④\b means backspace key, equivalent to back space key;
⑤\ ' denotes single quotation marks;
⑥\ ' means double quotation marks;
⑦\\ represents a slash \.
Java Fundamentals-Constants