Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 상수를 정의하는 데 final 키워드만 사용할 수 있습니까?

<시간/>

상수 변수는 값이 고정되어 있고 프로그램에 하나의 복사본만 존재하는 변수입니다. 상수 변수를 선언하고 값을 할당하면 프로그램 전체에서 해당 값을 다시 변경할 수 없습니다.

다른 언어와 달리 Java는 상수를 직접 지원하지 않습니다. 그러나 static 및 final 변수를 선언하여 상수를 생성할 수 있습니다. .

정적 − 변수를 static으로 선언하면 컴파일 시간에 메모리에 로드됩니다. 즉, 하나의 복사본만 사용할 수 있습니다.

최종 - 변수를 final로 선언하면 값을 다시 수정할 수 없습니다.

따라서 인스턴스 변수를 static 및 final로 선언하여 Java에서 상수를 생성할 수 있습니다.

예시

class Data {
   static final int integerConstant = 20;
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of integerConstant: "+Data.integerConstant);
   }
}

출력

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

정적 키워드가 없는 상수

static 키워드 없이 최종 변수를 생성하면 그 값은 수정할 수 없지만 새 객체를 생성할 때마다 변수의 별도 복사본이 생성됩니다.

예시

예를 들어, 다음 Java 프로그램을 고려하십시오.

class Data {
   final int integerConstant = 20;
}
public class ConstantExample {
   public static void main(String args[]) {
      Data obj1 = new Data();
      System.out.println("value of integerConstant: "+obj1.integerConstant);
      Data obj2 = new Data();
      System.out.println("value of integerConstant: "+obj2.integerConstant);
   }
}

출력

value of integerConstant: 20
value of integerConstant: 20

여기서 우리는 최종 변수를 만들고 두 개의 객체를 사용하여 그 값을 인쇄하려고 시도합니다. 변수의 값은 실제 변수의 복사본이므로 각각에 대해 다른 객체를 사용했기 때문에 두 인스턴스에서 변수 값이 동일하다고 생각했습니다.

상수의 정의에 따르면 프로그램(클래스) 전체에 걸쳐 변수의 단일 복사본이 필요합니다.

따라서 pert 정의로 상수를 생성하려면 static과 final을 모두 선언해야 합니다.