1. 程式人生 > >java程式設計思想 第二章 (一切都是物件)練習 2.11 練習1

java程式設計思想 第二章 (一切都是物件)練習 2.11 練習1

 

練習1:建立一個類,它包含一個int域和一個char域,它們都沒有被初始化,將他們的值打印出來,以驗證java執行了預設初始化。

 

 

public class Main {
    static int a;
    static char ch;
    public static void main(String[] args) {
        System.out.println(a);
        System.out.println(ch);
    }
}

輸出結果為:

0

 (因為沒有ch的值為null所以沒有列印任何字元)


Java類的成員變數在定義時會被預設初始化:

預設初始化規則
型別 初始化值
boolean

false

char

'\u0000'(null)

byte

(byte)0

short  

(short)0

int

0
long 0L
float 0.0f
double 0.0d

 

 

 

 

 

 

 

 

 

 

在方法中定義區域性變數時不會預設初始化。