Java中条件块中局部变量的初始化

Java包含5个条件块,即:if、switch、while、for和try。 在所有这些块中,如果指定的条件为真,则执行块内的代码,反之亦然。此外,Java编译器不允许您将局部变量保持未初始化状态。

null

在条件块内初始化局部变量时,必须记住以下3个细节: 1.如果指定的条件为真,并且条件中提供了“值”,则程序可以正常编译。 2.如果指定的条件为true,但条件中提供了“变量”,则会出现编译错误。 3.如果指定的条件为false,则会出现编译错误。

对于基元和引用类型的局部变量,上述给定点都是正确的。

例子: 下面的代码将给出一个编译错误。

// Java program to demonstrate error if we
// assign value to an uninitialized variable
// only in if block.
public class InitTesting {
public static void main(String args[])
{
int i = 100 ;
int j;
// Note that the condition is false
if (i > 500 )
j = i + 5 ;
System.out.println( "j :" + j);
}
}


 Output: 
prog.java:8: error: variable j might not have been initialized
        System.out.println("j :" + j);
                                   ^
1 error

if语句中的条件为false。因此,局部变量“j”永远不会初始化。因此,试图引用第8行中未初始化的变量“j”会导致编译错误。 要避免这种情况,请将局部变量初始化为条件块之外的默认值。 下面的代码运行良好-

// Java program to demonstrate that the above
// error is gone if we initialize the variable.
public class InitTesting {
public static void main(String args[])
{
int i = 100 ;
int j = 0 ;
// Note that the condition is false
if (i > 500 ) {
j = i + 5 ;
}
System.out.println( "j :" + j);
}
}


 Output:
j :0

此外,在Java中,“值”是在编译时读取的。但是,“变量”是在运行时读取的。因此,当变量是条件的一部分,并且在条件块内初始化了另一个变量时,会出现意外的编译时错误。

示例:查看下面的代码:

// Java program to demonstrate error even if
// condition is true.
class Test {
public static void main(String args[])
{
int a = 90 ;
int b = 80 ;
int i;
// The condition is true
if (a > b) {
i = a + 5 ;
}
System.out.println( "i :" + i);
}
}


 Output:
prog.java:9: error: variable i might not have been initialized
        System.out.println("i :" + i);
                                   ^
1 error

不管条件是真是假,它都会给出一个编译错误,因为Java在编译时没有读取变量,因此“i”没有初始化。

另一方面,如果指定值而不是变量,则不会发生这种情况。

// Java program to demonstrate that there is
// no error if we constants in if condition.
class Test {
public static void main(String args[])
{
int i;
if ( 90 > 80 ) {
i = a + 5 ;
}
System.out.println( "i :" + i);
}
}


 Output:
i :95
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享