Reputation: 49
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.
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". 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. But should not "final int x = 10;" throw compiler off-track as there is already x as a static variable?
Upvotes: 4
Views: 85
Reputation: 178263
Let's take this in code order.
static int x = 2;
This declares a static class variable named x
that is initialized to 2
.
if(x>1)
This refers to the static class variable, because the other declarations of x
haven't occurred yet.
x++;
This increments the static class variable x
to 3
.
int x = 4;
This declares a new local variable x
, distinct from the static class variable x
, and initializes it to 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. 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
. The local x
declared above is out of scope and no longer shadows the static class variable.
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
. 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. It is also not referenced after declaration and before it goes out of scope.
The main points are:
Upvotes: 5