Java 基本類型作為類的實例字段時,若未顯式初始化,JVM 會賦予確定的默認值。本文提供驗證代碼與標準對照表,助你快速記憶並避免 NPE/邏輯錯誤。
public class DefaultValueTest {
// 實例字段(非局部變量)
int a; // int
double b; // double
boolean c; // boolean
char d; // char
float f; // float
byte e; // byte
long h; // long
short j; // short
public static void main(String[] args) {
DefaultValueTest t = new DefaultValueTest();
System.out.println("int: " + t.a);
System.out.println("double: " + t.b);
System.out.println("boolean: " + t.c);
System.out.println("char: [" + t.d + "]"); // 不可見字符
System.out.println("byte: " + t.e);
System.out.println("float: " + t.f);
System.out.println("short: " + t.j);
System.out.println("long: " + t.h);
}
}
int: 0 double: 0.0 boolean: false char: byte: 0 float: 0.0 short: 0 long: 0
| 基本類型 | 位數 | 默認值 | 字面量表示 |
|---|---|---|---|
| byte | 8 | 0 | (byte)0 |
| short | 16 | 0 | (short)0 |
| int | 32 | 0 | 0 |
| long | 64 | 0L | 0L |
| float | 32 | 0.0f | 0.0f |
| double | 64 | 0.0d | 0.0d |
| char | 16 | '\u0000' | '\u0000' |
| boolean | 1 (JVM 實現相關) | false | false |
Integer obj; → null,拆箱時會拋 NPE' ' (0x0020)new int[3] → [0,0,0]數值類型全是零,
布爾默認假 (false),
字符空字符 (\u0000),
引用類型全是 null。
// ❌ 錯誤:局部變量未初始化
public void foo() {
int x;
System.out.println(x); // Compile Error: variable x might not have been initialized
}
// ✅ 正確:顯式初始化
public void foo() {
int x = 0; // 或直接使用字段 this.x
System.out.println(x);
}
// ⚠️ 危險:包裝類字段未初始化直接拆箱
private Integer count;
public void inc() {
count++; // NPE! 等同 count = count.intValue() + 1; count 為 null
}
// ✅ 修正
private Integer count = 0; // 或在構造器/聲明處初始化