Tuesday, 20 December 2011

04 - Scope and lifetime of variables

//Demostrating the scope of variables (local variables)

/*
    In java anything present in between { and } is treated as a block. For example:
   
    {
        Set of statements;
    }

    The above is a block. Also,

    if(condition)
    {
        Set of statements;
    }

    is also a block.

    So, now lets discuss about variables. In java there are four types of variables:
    1) Instance variables: Non-static variables declared inside a class.
    2) Class variables: Static variables declared inside a class.
    3) local variables: Variables declared within methods and within blocks.
    4) Parameters: These are also a type of local variables with respect to the method.

    Now, lets discuss about the scope of local variables:
    The scope of all the local variables and parameters is within the block in which they are declared.
    They cannot be accessed outside the block in which they are declared.

    Lets see this in the following example:
*/

class Box
{
    int length;
    int width;
    int height;

    void setDim(int l,int w,int h)
    {
        length = l;
        width = w;
        height = h;
    }
   
    void volume()
    {
        if(length!=0 && width!=0  && height!=0)
        {
            int vol = length*width*height;
            System.out.println("Volume of the Box is: "+vol);
        }
        //System.out.println("Volume of the Box is: "+vol);
    }
}

/*
    In the above code, if you see the volume() method, the "vol" variable is a local variable
    with respect to the "if" block. So, the scope of the "vol" variable is within the "if" block
    only. It cannot be accessed outside the "if" block.

    That is why the print statement after the "if" block is commented. If you remove the comments
    and excute the program, you will get an error. Try it!
*/

class BoxDemo
{
    public static void main(String args[])
    {
        Box b = new Box();
        b.setDim(10,20,30);
        b.volume();
    }
}

Downloading the program only: http://paste2.org/followup/1832512

No comments:

Post a Comment