如何在 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);
   }
}

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

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

更新日期: 2019 年 7 月 30 日

一千次以上浏览

开启您的 职业

完成课程获得认证

开始
广告