Question:
Based on my reference, primitive types have default values and Objects are null. I tested a piece of code using both NetBeans and Eclipse.
public class Main {
public static void main(String[] args) {
int a;
System.out.println(a);
}
}
Using both IDE, the line System.out.println(a); will be an error pointing at the variable a that saysvariable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.
public class Main {
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
What could possibly go wrong with the first code? Does instance variable behaves different from local variables?
Answer:
In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.
In the second code sample, a is class member variable, hence it will be initialized to default value .
本文探讨了Java中局部变量与成员变量的初始化问题。通过两个代码示例对比,解释了为什么局部变量需要显式初始化,而成员变量则会默认初始化为特定值。
954

被折叠的 条评论
为什么被折叠?



