Java의 기본값 및 초기화
내 참조에 따르면 기본 유형에는 기본값이 있고 Objects는 null입니다. 코드를 테스트했습니다.
public class Main {
public static void main(String[] args) {
int a;
System.out.println(a);
}
}
라인이 System.out.println(a);변수 가리키는 오류가있을 것이다 a라고 variable a might not have been initialized주어진 기준에있는 반면에, integer해야합니다 0기본 값으로. 그러나 아래 주어진 코드를 사용하면 실제로 0.
public class Main {
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
첫 번째 코드에서 무엇이 잘못 될 수 있습니까? 클래스
인스턴스
변수가 지역 변수와 다르게 동작 합니까
?
첫 번째 코드 샘플에서, aA는 main방법 로컬 변수. 메서드 지역 변수는 사용하기 전에 초기화해야합니다.
두 번째 코드 샘플에서는 a클래스 멤버 변수이므로 기본값으로 초기화됩니다.
참조를 자세히 읽어보십시오 .
기본값
필드 가 선언 될 때 항상 값을 할당 할 필요는 없습니다 . 선언되었지만 초기화되지 않은 필드 는 컴파일러에 의해 적절한 기본값으로 설정됩니다. 일반적으로이 기본값은 데이터 유형에 따라 0 또는 널입니다. 그러나 이러한 기본값에 의존하는 것은 일반적으로 잘못된 프로그래밍 스타일로 간주됩니다.
다음 차트는 위 데이터 유형의 기본값을 요약 한 것입니다.
. . .
지역 변수는 약간 다릅니다. 컴파일러는 초기화되지 않은 지역 변수에 기본값을 할당하지 않습니다. 선언 된 지역 변수를 초기화 할 수없는 경우 사용하기 전에 값을 할당해야합니다. 초기화되지 않은 로컬 변수에 액세스하면 컴파일 타임 오류가 발생합니다.
관련된 주요 요소는 다음과 같습니다.
- 멤버 변수 (기본값 OK)
- 정적 변수 (기본값 OK)
- 최종 멤버 변수 (초기화되지 않음, 생성자에 설정해야 함)
- 최종 정적 변수 (초기화되지 않음, 정적 블록 {}에 설정해야 함)
- 지역 변수 (초기화되지 않음)
참고 1 : 모든 구현 생성자에서 최종 멤버 변수를 초기화해야합니다!
참고 2 : 생성자 자체의 블록 내에서 최종 멤버 변수를 초기화해야하며 초기화하는 다른 메서드를 호출하지 않아야합니다. 예를 들어 이것은 유효하지 않습니다.
private final int memberVar;
public Foo() {
//invalid initialization of a final member
init();
}
private void init() {
memberVar = 10;
}
참고 3 : 배열은 기본 요소를 저장하더라도 Java의 객체입니다.
참고 4 : 배열을 초기화하면 모든 항목이 구성원 또는 로컬 배열과 관계없이 기본값으로 설정됩니다.
앞서 언급 한 사례를 제시하는 코드 예제를 첨부하고 있습니다.
public class Foo {
//static and member variables are initialized to default values
//primitives
private int a; //default 0
private static int b; //default 0
//objects
private Object c; //default NULL
private static Object d; //default NULL
//arrays (Note: they are objects too, even if they store primitives)
private int[] e; //default NULL
private static int[] f; //default NULL
//what if declared as final?
//primitives
private final int g; //not initialized, MUST set in constructor
private final static int h; //not initialized, MUST set in a static {}
//objects
private final Object i; //not initialized, MUST set in constructor
private final static Object j; //not initialized, MUST set in a static {}
//arrays
private final int[] k; //not initialized, MUST set in constructor
private final static int[] l; //not initialized, MUST set in a static {}
//initialize final statics
static {
h = 5;
j = new Object();
l = new int[5]; //elements of l are initialized to 0
}
//initialize final member variables
public Foo() {
g = 10;
i = new Object();
k = new int[10]; //elements of k are initialized to 0
}
//A second example constructor
//you have to initialize final member variables to every constructor!
public Foo(boolean aBoolean) {
g = 15;
i = new Object();
k = new int[15]; //elements of k are initialized to 0
}
public static void main(String[] args) {
//local variables are not initialized
int m; //not initialized
Object n; //not initialized
int[] o; //not initialized
//we must initialize them before usage
m = 20;
n = new Object();
o = new int[20]; //elements of o are initialized to 0
}
}
기본 유형 값을 선언 할 때 유의해야 할 몇 가지 사항이 있습니다.
그들은:
- 메서드 내에서 선언 된 값에는 기본값이 할당되지 않습니다.
- 인스턴스 변수 또는 정적 변수로 선언 된 값은 0 인 기본값이 할당됩니다.
따라서 코드에서 :
public class Main {
int instanceVariable;
static int staticVariable;
public static void main(String[] args) {
Main mainInstance = new Main()
int localVariable;
int localVariableTwo = 2;
System.out.println(mainInstance.instanceVariable);
System.out.println(staticVariable);
// System.out.println(localVariable); //will throw compilation error
System.out.println(localVariableTwo);
}
}
예, 인스턴스 변수는 기본값으로 초기화됩니다. 로컬 변수는 사용하기 전에 초기화해야합니다.
public class Main {
int instaceVariable; // Instance variable will be initalized to default value
public static void main(String[] args) {
int localVariable = 0; // Local Variable Need to initalize before use
}
}
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.
All member variable have to load into heap so they have to initialized with default values when an instance of class is created. In case of local variables, they don't get loaded into heap they are stored in stack until they are being used before java 7, so we need to explicitly initialize them.
In java the default initialization is applicable for only instance variable of class member it isn't applicable for local variables.
참고URL : https://stackoverflow.com/questions/19131336/default-values-and-initialization-in-java
'program story' 카테고리의 다른 글
| Entity Framework 5 엔터티의 전체 복사 / 복제 (0) | 2020.11.04 |
|---|---|
| JavaScript에서 정규식 패턴으로 동적 (변수) 문자열 사용 (0) | 2020.11.04 |
| 일반 유형 검사 (0) | 2020.11.04 |
| PHP : 괄호 안의 텍스트를 추출하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.04 |
| 어떤 Lisp를 배워야합니까? (0) | 2020.11.03 |