为什么下面的Java程序不给出错误?
为什么对为什么下面的Java程序不给出错误?,java,Java,为什么对int j的多个声明不给出错误?因为第一个j在然后是分支,而第二个在其他分支 else,然后有两个不同的作用域,因此,如果以这种方式声明相同的变量,则没有问题 范围由{和}分隔 您的代码与此相同: public class Main { public static void main(String[] args) { int i=0; if( i == 0){ int j; } else{
int j
的多个声明不给出错误?因为第一个j
在然后是分支,而第二个在其他分支
else,然后有两个不同的作用域,因此,如果以这种方式声明相同的变量,则没有问题
范围由{
和}
分隔
您的代码与此相同:
public class Main {
public static void main(String[] args) {
int i=0;
if( i == 0){
int j;
}
else{
int j;
}
}
}
因为两个“j”都在不同的范围内,一个在If分支中,另一个在else分支中
public class Main {
public static void main(String[] args) {
int i=0;
int j;
if( i == 0){
j = 1;
}
else{
j = 2;
}
}
}
在java中,有一种称为作用域的东西。如果在括号内声明变量,则只有在这些括号内才知道该变量 比如说,
if(i == 0) { // First scope starts
int j;
} // First scope ends if j destroyed here
else { // Second scope starts
int j;
} // Second scope ends else j destroyed here
if
和else
都有不同的作用域
if
中声明的变量只能在if
及其任何子项中使用
类似地,在else
中声明的变量只能在else
及其任何子项中使用
有关变量作用域的更多信息,请阅读。将只执行一个作用域,因此只创建一个j。它不会进入if范围如果条件(i==0)不为true,它将进入else范围并创建整数j。如果(i==0),它将进入if范围并创建j;它永远不会进入其他范围。所以无论如何,变量j只声明一次。这只是因为局部变量的作用域,只要打开一个块(
{
)并关闭一个块(}
),局部变量就有作用域
在这里,您将在两个块内声明一个intj
public static void main(String[] args)
{
if(true)
{
int jellyBean = 100;
System.out.println("You can use this variable here" + jellyBean );
}//When the code comes to this bracket, the jellyBean variable is destroyed and can be redeclared.
System.out.println("You cannot use this variable here because it's not declared" + jellyBean );//Will produce error
int jellyBean = 10; //Perfectly valid code because the previous variable has been destroyed
}
java编译器知道在不同的作用域中有两个
j
,查看变量作用域。
public class Main {
public static void main(String[] args) {
int i=0;
if( i == 0){
int j; // here j has scoped in if block
}
else{
int j; // and here j has scoped in else block
}
}
}