由於Java不像其他編程語言那樣直接支持常量聲明,因此不能使變量成為常量。我們可以聲明一個變量static final。
靜態定義變量可以在不加載類的瞬間的情況下進行訪問,而final定義在程序執行期間不能更改該值。
final static datatype constant_name = value;
注意:在聲明常量時–必須指定值。
例:
final static int MAX = 100;
Java代碼聲明和打印常量
// 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); } }
輸出量
value of MAX = 100 value of DEFAULT = N/A value of PI = 3.14