關於預設初始化

來源:互聯網
上載者:User

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.關於預設值說明

若某個主要資料類型屬於一個類成員,那麼即使不明確(顯式)進行初始化,也可以保證它們獲得一個預設值,這種保證卻並不適用於“局部”變數——那些變數並非一個類的欄位。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.