在Java中,常量是指在程序運行過程中值不會改變的量。為了聲明和使用常量,你需要遵循以下步驟:
final
關鍵字聲明常量。下面是一個聲明和使用常量的示例:
public class Constants {
// 聲明一個整型常量,名為MAX_VALUE,值為100
public static final int MAX_VALUE = 100;
// 聲明一個字符串常量,名為GREETING,值為"Hello, World!"
public static final String GREETING = "Hello, World!";
}
在其他類中使用這些常量:
public class Main {
public static void main(String[] args) {
// 使用常量MAX_VALUE
int maxValue = Constants.MAX_VALUE;
System.out.println("The maximum value is: " + maxValue);
// 使用常量GREETING
String greeting = Constants.GREETING;
System.out.println("The greeting is: " + greeting);
}
}
輸出結果:
The maximum value is: 100
The greeting is: Hello, World!