[英]Java8 variables scope
I took mock exam test as i am preparing for OCAJP exam and i came across this below question on Variables and Scope of Variables. 当我准备参加OCAJP考试时,我参加了模拟考试,我在下面的变量和变量范围问题上遇到了这个问题。
public class HelloWorld{
static int x = 2;
public static void main(String []args){
if(x>1)
{
x++;
int x = 4;
}
System.out.println(x);
final int x = 10;
}
}
and the output for the above code is "3". 并且上述代码的输出为“3”。 But i am unable to figure out why the output is 3. I can understand that the "int x=4" within the if block will be seen outside the IF block.
但是我无法弄清楚为什么输出是3.我可以理解if块中的“int x = 4”将在IF块之外看到。 But should not "final int x = 10;"
但不应该“最终int x = 10;” throw compiler off-track as there is already x as a static variable?
抛出编译器偏离轨道,因为已经有x作为静态变量?
Let's take this in code order. 我们按照代码顺序来看一下。
static int x = 2;
This declares a static class variable named x
that is initialized to 2
. 这声明了一个名为
x
的静态类变量,它初始化为2
。
if(x>1)
This refers to the static class variable, because the other declarations of x
haven't occurred yet. 这是指静态类变量,因为
x
的其他声明尚未发生。
x++;
This increments the static class variable x
to 3
. 这会将静态类变量
x
递增为3
。
int x = 4;
This declares a new local variable x
, distinct from the static class variable x
, and initializes it to 4
. 这声明了一个新的局部变量
x
,它与静态类变量x
,并将其初始化为4
。 This new local variable shadows the static class variable. 这个新的局部变量会影响静态类变量。 However, it immediately goes out of scope;
但是,它立即超出了范围; its scope is limited to the
if
block. 其范围仅限于
if
块。 It is not referenced after declaration and before it goes out of scope. 声明之后以及超出范围之前不会引用它。
System.out.println(x);
This prints the only x
in scope, the static class variable, which is 3
. 这将打印范围中唯一的
x
,静态类变量,即3
。 The local x
declared above is out of scope and no longer shadows the static class variable. 上面声明的局部
x
超出范围,不再隐藏静态类变量。
final int x = 10;
This declare another new local variable x
, also distinct from the static class variable x
and distinct from the already out of scope x
previously declared in the if
block, and initializes it to 10
. 这声明了另一个新的局部变量
x
,它也与静态类变量x
不同,并且与先前在if
块中声明的已经超出范围x
不同,并将其初始化为10
。 This new local variable shadows the static class variable. 这个新的局部变量会影响静态类变量。 However, it also immediately goes out of scope;
但是,它也立即超出了范围; its scope is limited to the
main
method block. 其范围仅限于
main
方法块。 It is also not referenced after declaration and before it goes out of scope. 声明之后以及超出范围之前也不会引用它。
The main points are: 要点是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.