What is Block Structure
What is Block Structure
Scope Concepts
Scope refers to the region of the program where a variable is accessible. Two
common scope mechanisms are static scope (lexical scope) and dynamic scope.
as context.
● The compiler identifies the scope of a variable based on the block in which it
is declared.
● Variables declared in an inner block can shadow variables with the same
name in outer blocks.
Example in Java:
public class StaticScopeExample {
static int globalVar = 50; // Class-level (global) scope
// Nested block
{
int y = 20; // Local to this block
int globalVar = 100; // Shadows the global variable
System.out.println("Block Variable y: " + y);
System.out.println("Shadowed Global Variable: " + globalVar);
}
// Uncommenting the below line will cause an error since y is out of scope
// System.out.println(y);
}
}
Output:
Global Variable: 50
Local Variable x: 10
Block Variable y: 20
Shadowed Global Variable: 100
Restored Global Variable: 50
Explanation:
2. Dynamic Scope
Java does not support dynamic scoping natively. However, it can be simulated
using global variables or thread-local storage, where a variable's value is
determined dynamically based on the runtime context.
Output:
Main starts with dynamicVar: 50
Function1 changes dynamicVar to: 100
Function2 accesses dynamicVar: 100
Explanation:
By leveraging block structure and static scoping, Java ensures clear and predictable
variable resolution, promoting modularity and reducing bugs caused by unexpected
variable accesses.