Exercise 1: (2) Create a class containing an int and a char that are not initialized, and print their values to verify that Java performs default
initialization.
練習:建立一個類,他包含一個int域和一個char域,他們沒有被初始化,將他們的值列印出來,以驗證Java執行力預設初始化。
能啟動並執行程式如下:
public class Ex1 { static int i; static char ch; public static void main(String[] args) { System.out.println("The default value for \"int\" is"+i); System.out.println("The default value for \"char\" is"+ch); }}
錯誤1:
public class Ex1 { public static void main(String[] args) { static int i; static char ch; System.out.println("The default value for \"int\" is"+i); System.out.println("The default value for \"char\" is"+ch); }}
錯誤2:
public class Ex1 { public static void main(String[] args) { int i; char ch; System.out.println("The default value for \"int\" is"+i); System.out.println("The default value for \"char\" is"+ch); }}
注意點:
1.錯誤1說明
The default values are only what
Java guarantees when the variable is used as a member of a class. This ensures that member variables of primitive types will always be initialized (something C++ doesn’t do), reducing a source of bugs. However, this initial value may not be correct or even
legal for the program you are writing. It’s best to always explicitly initialize your variables.
2.錯誤2說明
關於Static的關鍵字的用法,static variable有什麼作用,下面就有描述:
One is if you want to have only a single piece of storage for a particular field, regardless of how many objects of that class are created, or even if no objects are created. The other is if you need a method that isn’t associated with any particular object
of this class. That is, you need a method that you can call even if no objects are created.
3.關於預設值說明
若某個主要資料類型屬於一個類成員,那麼即使不明確(顯式)進行初始化,也可以保證它們獲得一個預設值,這種保證卻並不適用於“局部”變數——那些變數並非一個類的欄位。