所有代码都使用Java。
public class TestLocal
{
public static void main(String [] args)
{
int x;
if (args[0] != null)
{ // assume you know this will
// always be true
x = 7; // statement will run
}
int y = x; // the compiler will choke here
}
}
所以,我的问题是为什么编译器会在这里阻塞?它会绕过if语句吗(看起来很可怕...)如果我在if语句块之外初始化x,则编译器不会抱怨,如以下代码所示:
public class TestLocal
{
public static void main(String [] args)
{
int x;
x = 7; // compiler is happy now..:)
if (args[0] != null)
{ // assume you know this will
// always be true
// statement will run
}
int y = x; // the compiler not complain here now.
}
}
为什么编译器会出现这种可怕的行为?
Java要求您初始化局部变量作为一种安全措施。它可以防止您意外读取奇数值。如果编译器没有抱怨,而您要读取x的值,则可能是任何值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句