CODE
class ScopeInSameBlock
{
public static void main(String arg[])
{
int x = 15; // LINE A
int y = x; // LINE B
int z = y + 20; // LINE C
System.out.println("x = " + x); // LINE D
System.out.println("y = " + y); // LINE E
System.out.println("z = " + z); // LINE F
}
}
x = 15
y = 15
z = 35
Any variable will be valid in the statements below its declaration. It will not be valid before it is declared. Here x
is in scope in all lines below LINE A
, until the end of the block. Where as y
is valid in lines below LINE B
and z
is valid (or in scope) after LINE C
. Using any variable not in scope will throw an 'undefined variable' compilation error.
LINE B
above LINE A
.LINE D
above LINE B
or try moving LINE F
above LINE B