Computer Applications
Explain the scope of variables in blocks and sub-blocks.
Encapsulation & Inheritance in Java
2 Likes
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.
Answered By
1 Like