簡體   English   中英

Java初始化時出現意外行為

[英]Unexpected behaviour with Java initialization

注意:我很清楚初始化它可以解決問題; 我只是假設編譯器會遵循執行路徑,並且看到foo實際上會在它建議'可能'不是的時候進行初始化。

我最初的假設是,如果長度從未超過3,我將永遠不需要為它使用分配內存。

這永遠不會用於生產,我只是好奇

請參閱以下示例: -

List<String> foo;

int length = 5;

if (length > 3)
{
    foo = new ArrayList<String>();
}

if (length > 4)
{
    foo.add("bar");
}

為什么會導致顯示以下內容?

局部變量foo可能尚未初始化

當然,在分支之后,永遠不會出現foo未初始化的情況。 我知道如果我這樣做: -

List<String> foo = null;

沒有編譯問題,但為什么我需要這樣做呢?

如果將輸入塊,編譯器無法確定您是第一個。 如果沒有,那么foo將保持未初始化狀態。 你不能在未初始化的變量上調用add 您可以通過最終length來幫助編譯器。 然后編譯器將知道將執行第一個if塊。

final int length = 5;

局部變量需要在其他地方使用之前進行初始化,因為默認情況下不會對其進行初始化。如果if()不為true怎么辦?

if (length > 3)
{
    foo = new ArrayList<String>();
}

編譯器無法判斷條件是否為真。

局部變量(§14.4,§14.13)必須在使用之前通過初始化(§14.4)或賦值(§15.26)顯式賦予一個值,編程方式可以使用定義規則進行驗證。分配

由於@jlordo指出將length設為final將解決編譯錯誤,因為在編譯時本身編譯器知道length的值總是為5 ,因此條件length>3總是為true所以局部變量將是初始化。

因為默認情況下未初始化本地實例,與類或對象實例不同。

Java語言規范

局部變量(§14.4,§14.14)必須在使用之前通過初始化(§14.4)或賦值(§15.26)顯式賦予一個值,編程方式可以使用定義規則進行驗證。任務(§16)。

默認值:

For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null. 

發生這種情況是因為foo在分支中初始化。 所以編譯器不確定foo是否會被初始化。

實例和類變量初始化為null或0值。 但局部變量不是。 因此,您必須在使用之前初始化局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM