問題描述
請看下面的代碼.方法 printTest() 正在打印未初始化變量的默認值,但是當涉及到 main 方法時,java 要求進行變量初始化.誰能解釋一下為什么?
Please see the code below. The method printTest() is printing the default value of the uninitialized variables but when it's comes to main method java is asking for variable initialization. Can anybody explain why?
public class Test1 {
public static void main(String[] args) {
int j;
String t;
System.out.println(j);
System.out.println(t);
}
}
public class Test2 {
int i;
String test;
public static void main(String[] args) {
new Test().printTest();
}
void printTest() {
System.out.println(i);
System.out.println(test);
}
}
推薦答案
局部變量主要用于中間計算,而實例變量應該攜帶用于未來和中間計算的數據.Java 不強制初始化實例變量并允許默認值,但對于局部變量,開發人員調用它來分配值.所以為了避免錯誤,你需要初始化局部變量.
Local variables are used mostly for intermediate calculations whereas instance variables are supposed to carry data for calculations for future and intermediate as well. Java doesnt forces to initialize instance variable and allows default value but for local variables its the developers call to adssign the value. So to avoid mistakes you need to initialize local variables.
這篇關于為什么java在本地時要求初始化變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!