ICSE Class 10 Computer Applications Question 6 of 16

Encapsulation and Inheritance — Question 7

Back to all questions
7
Question

Question 7

Explain the scope of variables in blocks and sub-blocks.

Answer

A variable declared in a block is visible (accessible) in the block and in all the sub-blocks. However, it is not visible outside the block.
Consider the given example:

void Add()  {
    int a = 10; 
    int b = 20;
    if(a < b)   {      //Block 1
        int sum = a + b;
        System.out.println(sum);
    }
    else    {       //Block 2
        int diff = a - b;
        System.out.println(diff);
    }
}

Here, the variables a and b will be accessible throughout the block and its sub-blocks (Block 1 and Block 2) but the variable sum will be accessible only in Block 1 and the variable diff will be accessible only in Block 2.