如何在 java 中實現常量?


常數變數的值是固定,程式中只有一個副本。一旦宣告常量變數並賦予它值,在整個程式中就不能再更改其值。

可以使用常量關鍵字(建立它的方法之一)在 c 語言中建立常量,如下 -

const int intererConstant = 100;
or,
const float floatConstant = 16.254;
….. etc

java 中的常量

與 C 語言不同,java 中不支援常量(直接)。但是,仍然可以透過宣告變數 static 和 final 來建立常量。

static - 一旦宣告變數為 static,它們將在編譯時載入到記憶體中,即只提供了一個副本。

final - 一旦宣告變數為 final,就不能再修改其值。

因此,可以透過宣告例項變數 static 和 final 來在 Java 中建立常量。

示例

在以下 Java 示例中,在一個類(名為 Data)中有 5 個常量(static 和 final 變數),並從另一個類的 main 方法中訪問它們。

class Data{
   static final int integerConstant = 20;
   static final String stringConstant = "hello";
   static final float floatConstant = 1654.22f;
   static final char characterConstant = 'C';
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of integerConstant: "+Data.integerConstant);
      System.out.println("value of stringConstant: "+Data.stringConstant);
      System.out.println("value of floatConstant: "+Data.floatConstant);
      System.out.println("value of characterConstant: "+Data.characterConstant);
   }
}

輸出

value of integerConstant: 20
value of stringConstant: hello
value of floatConstant: 1654.22
value of characterConstant: C

更新日期: 2019 年 7 月 30 日

一千次以上瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告