public class TestIf {
public static void main(String[] args) {
int i = 30;
int j;
if(i > 20) {
j = 10;
System.out.println("j=" + j);
}
}
}
程序编译成功,并运行输出10,为什么j没被初始化就能使用??既然j能在IF方法中才被初始化,并输出,为什么第二个不行?public class TestIf {
public static void main(String[] args) {
int i = 30;
int j;
if(i > 20) {
j = 10;
}
System.out.println("j=" + j);
}
}
程序编译失败,显示:可能尚未初始化变量j。为什么上面的能成功编译,下面的不行?public class TestIf {
public static void main(String[] args) {
int i = 30;
int j = 3;
if(i > 20) {
j = 10;
}
System.out.println("j=" + j);
}
}
程序编译成功,并运行输出10. 第一个程序,j是在IF方法中才被初始化赋值,并在方法中用System.out.println输出值10,但在第二个程序中,System.out.println不在IF方法内,编译不成功,显示j未被初始化。第三个程序,System.out.println在IF方法外,但j早已被初始化为3,并在IF方法内被赋值10,跟着被输出10.
public static void main(String[] args) {
int i = 30;
int j;
if(i > 20) {
j = 10;
System.out.println("j=" + j);
}
}
}
程序编译成功,并运行输出10,为什么j没被初始化就能使用??既然j能在IF方法中才被初始化,并输出,为什么第二个不行?public class TestIf {
public static void main(String[] args) {
int i = 30;
int j;
if(i > 20) {
j = 10;
}
System.out.println("j=" + j);
}
}
程序编译失败,显示:可能尚未初始化变量j。为什么上面的能成功编译,下面的不行?public class TestIf {
public static void main(String[] args) {
int i = 30;
int j = 3;
if(i > 20) {
j = 10;
}
System.out.println("j=" + j);
}
}
程序编译成功,并运行输出10. 第一个程序,j是在IF方法中才被初始化赋值,并在方法中用System.out.println输出值10,但在第二个程序中,System.out.println不在IF方法内,编译不成功,显示j未被初始化。第三个程序,System.out.println在IF方法外,但j早已被初始化为3,并在IF方法内被赋值10,跟着被输出10.
但是第二个程序 调用System.out.println("j="+j)的时候j不一定被初始化,因此编译失败,第三个同理。
第二个程序明显有2种执行路径,就是在if那里,而如果没有执行if,然后System.out.println("j="+j)。这样是不合法的,因为j没初始化。
在java中,int j,算定义吧,和C有点区别。