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

Java에서 상수와 최종 변수의 차이점은 무엇입니까?

<시간/>

자바의 상수

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

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

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

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

예시

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

자바의 최종 변수

변수를 final로 선언하면 값을 변경할 수 없습니다. 그렇게 하려고 하면 컴파일 시간 오류가 발생합니다.

예시

public class FinalExample {
   public static void main(String args[]) {
      final int num = 200;
      num = 2544;
   }
}

출력

FinalExample.java:4: error: cannot assign a value to final variable num
   num = 2544;
   ^
1 error

최종 변수와 상수(정적 및 최종)의 주요 차이점은 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을 모두 선언해야 합니다.