This will compile
class X
{
public static void main(String args[])
{
{
int a = 2;
}
{
int a = 3;
}
}
}
This won't
class X
{
public static void main(String args[])
{
int a = 2;
{
int a = 3;
}
}
}
I expected both to compile (maybe it is the way C works?). What is the reason because it is not possible to declare a variable in a block with the same name of one in the outer block?
Java doesn't allow you to have two variables with the same name within scope of one another.
In your second case:
However, in your first case, each
a
is contained within its own scope, so all is well.In the example above you declared
a
in you methodmain()
. From the declaration till the end of the method,a
is declared. In this case you cannout redeclare a in you codeblock.Below, you declare
a
in a block. It is only known insside.Because in the second case
a
is known inside the static block, so you're trying to redeclare it. The compiler doesn't allow you to do so:The short answer is: Because this is the way the Java language is defined in JLS §6.4.
You might be used from other languages that this so called variable shadowing is allowed. However, the inventors of the Java languages thought this was an awkward feature that they did not want in their language:
However, you find shadowing elsewhere in Java as the authors state in the same section of the JLS:
This means in practice that the following code is legal:
As the authors describe, it is allowed to shadow an instance variable by declaring a method local variable with the same name because of the possibility of someone extending the functionality of
A
at one day where you could not longer compile a classB
if shadowing was illegal:If you consider a language like C, where shadowing is allowed, you can find awkward code like this:
This program is not so easy to follow and might therefore not produce the results you expect, thanks to variable shadowing.
In Java all local variables will be stored on Stack. So if u write
Hope this help you out
Thanks