java 声明一个常量
Since, Java does not support constant declaration directly like other programming languages, to make a variable constant; we can declare a variable static final.
由于Java不像其他编程语言那样直接支持常量声明 ,因此不能使变量成为常量 。 我们可以声明一个变量static final 。
The static defines that variable can be accessed without loading the instant of the class and final defines that the value cannot be changed during the program execution.
静态定义变量可以在不加载类的瞬间的情况下进行访问,而final定义在程序执行期间不能更改该值。
Syntax:
句法:
final static datatype constant_name = value;
Note: While declaring a constant – it is mandatory to assign the value.
注意:在声明常量时 –必须指定值。
Example:
例:
final static int MAX = 100;
Java代码声明和打印常量 (Java code to declare and print the constant)
// Java code to declare and print the constant
public class Main {
//integer constant
final static int MAX = 100;
//string constant
final static String DEFAULT = "N/A";
//float constant
final static float PI = 3.14f;
public static void main(String[] args) {
//printing the constant values
System.out.println("value of MAX = " + MAX);
System.out.println("value of DEFAULT = " + DEFAULT);
System.out.println("value of PI = " + PI);
}
}
Output
输出量
value of MAX = 100
value of DEFAULT = N/A
value of PI = 3.14
翻译自: https://www.includehelp.com/java-programs/declaring-a-constant-in-java.aspx
java 声明一个常量