2015-02-17 15 views
0

新手問題。Java:僅在變量爲本地時打印Uninitalized Integer纔有錯誤

爲什麼第一個代碼段輸出「0」而第二個代碼段返回錯誤?

無錯誤的代碼。

test.java:12: error: variable i might not have been initialized 
     System.out.println(i); 
         ^

編譯第二代碼段與Eclipse的

- 不編譯

int i; 
System.out.println(i); //returns a error in main method as well as other methods. 

編譯第二代碼段用javac終端命令(OS X)

public class test 
{ 
    public int c; 
    public test() 
    { 
     System.out.println(c); //prints out 0 
    } 
    public static void main(String args[]) 
    { 
     test t = new test(); 
     t.printC(); 
    } 
} 

代碼

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The local variable i may not have been initialized 

    at test.test.main(test.java:14) 
+1

需要初始化局部變量。然而,一個實例變量隱含地初始化爲其默認值(對於一個int爲0)。 Eclipse使用它自己的編譯器,它替換了未由錯誤編譯的代碼;這就是爲什麼你能夠運行代碼。 – 2015-02-17 22:36:24

+0

@鄒鄒感謝您的快速回復。這是爲什麼? – champfish 2015-02-17 22:38:51

+0

因爲這是行爲在JLS§16中定義的方式。 – 2015-02-17 22:41:35

回答

0

As @ZouZou鏈接到局部變量必須始終被初始化,但實例變量不會。這是因爲編譯器無法知道正在調用什麼順序方法,因此不知道實例變量是否已被初始化。

相關問題