首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 8 大基本類型默認值一覽表與驗證代碼

     編輯:Java 綜合教學

Java 8 大基本類型默認值一覽表與驗證代碼

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

標準默認值對照表

基本類型位數默認值字面量表示
byte80(byte)0
short160(short)0
int3200
long640L0L
float320.0f0.0f
double640.0d0.0d
char16'\u0000''\u0000'
boolean1 (JVM 實現相關)falsefalse

關鍵注意事項

  • 僅限實例字段/靜態字段/數組元素:方法內局部變量無默認值,使用前必須賦值,否則編譯報錯
  • 包裝類默認值為 null:Integer obj; → null,拆箱時會拋 NPE
  • char 默認值 '\u0000':不可見字符,非空格 ' ' (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; // 或在構造器/聲明處初始化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved