Commit cef67ee
committed
feat: Add Scope class to demonstrate variable scope and shadowing in Java
WHAT the code does:
- Defines a `Scope` class to illustrate how variable scope works in Java.
- Shows that variables declared outside a block can be reassigned inside it.
- Demonstrates block-scoped variables that cannot be accessed outside the block.
- Shows loop-scoped variables (`i` and `num` inside the `for` loop).
- Provides a `random(int marks)` method with its own local scope.
WHY this matters:
- Helps understand **scope, shadowing, and lifetime of variables** in Java.
- Reinforces that variables with the same name cannot be redeclared in the same scope.
- Clarifies the difference between reassignment and re-declaration.
- Teaches best practices for avoiding naming conflicts.
HOW it works:
1. Declares `a`, `b`, and `name` in `main()`.
2. Inside a block:
- Reassigns `a = 100`.
- Defines a new block-scoped variable `c = 99`.
- Changes `name` to `"Rahul"`.
3. After block:
- Creates a new `c = 900` (different from block’s `c`).
- Prints updated values of `a`, `name`, and `c`.
4. In the `for` loop:
- `i` and `num` exist only inside the loop body.
- `a` is reassigned to `10000` in each iteration.
5. `random()` method:
- Defines local `num = 67`.
- Prints both local `num` and parameter `marks`.
Tips & gotchas:
- Attempting to redeclare `a` inside the block would cause a compile error due to shadowing rules.
- Variables declared in a block (`{}`) cannot be accessed outside of it.
- Loop counters and local variables are destroyed once the block exits.
- Good practice: use descriptive names to avoid shadowing confusion.
Use-cases:
- Educational example to teach **variable scope and shadowing**.
- Helps beginners avoid common compile-time errors with redeclaration.
- Foundation for understanding **memory management and lifetime** of variables.
- Useful in debugging scoping issues in larger codebases.
Short key: class-scope-variable-shadowing.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 98eb17b commit cef67ee
1 file changed
+15
-12
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
| 5 | + | |
| 6 | + | |
6 | 7 | | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
14 | 19 | | |
15 | 20 | | |
16 | 21 | | |
17 | 22 | | |
18 | | - | |
| 23 | + | |
19 | 24 | | |
20 | | - | |
21 | 25 | | |
22 | | - | |
| 26 | + | |
23 | 27 | | |
24 | 28 | | |
25 | 29 | | |
26 | 30 | | |
27 | 31 | | |
28 | | - | |
29 | 32 | | |
30 | 33 | | |
31 | 34 | | |
| |||
0 commit comments