Menu
Topics Index
...
`


Variables >
Siva Nookala - 12 Apr 2016
Scope of variable is nothing but the statements or expressions in which the variable can be used. Any variable is in scope ( valid ) in the statements below its declaration. It will not be in scope or it will be invalid above its declaration.

Scope in same block
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
    
    }
}
OUTPUT

x = 15
y = 15
z = 35

DESCRIPTION

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.

THINGS TO TRY
  • Change the order of lines - put LINE B above LINE A.
  • Move LINE D above LINE B or try moving LINE F above LINE B

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.

Learn Java Programming from our Experts in 30 Days