Skip to content

Commit 2ed49cd

Browse files
committed
feat: Demonstrate static vs local variable behavior across multiple method calls [static-local-scope]
🔑 Key: static-local-scope 🧠 Logic: - `static int a = 10`: A class-level variable shared across all instances; retains value across method calls. - `int b = 10`: A method-local variable, freshly created on each method call. - Method `fun()` prints `a` and `b`, then increments both. - `++a`: Affects the shared static value (persistent across calls). - `++b`: Affects the temporary local value (discarded after each call). 📌 Observations: - First call to `fun()` → prints `10 10`, then increments `a` to `11`. - Second call → prints `11 10`, because `a` retained its value while `b` re-initialized. 🎯 Concept Reinforced: - Difference between static and local variables: - Static memory: One copy shared → used when persistence is needed. - Local stack memory: Temporary → used for short-lived calculations or logic. 📚 Learning Use: - Clarifies variable scope and lifetime. - Useful for understanding memory model, especially in OOP design and interview questions. Signed-off-by: Somesh diwan <[email protected]>
1 parent 7a5d1e2 commit 2ed49cd

File tree

2 files changed

+33
-13
lines changed

2 files changed

+33
-13
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
public class StaticVariableDemo {
2+
3+
// 🔁 Static variable: belongs to the class, only one copy shared across all instances
4+
static int a = 10;
5+
6+
void fun() {
7+
// 🔁 Local variable: created fresh every time the method is called
8+
int b = 10;
9+
10+
// Print current values of a (static) and b (local)
11+
System.out.println(a + " " + b);
12+
13+
// 🔼 ++a updates the shared static value, persists across calls
14+
++a;
15+
16+
// 🔁 ++b updates the local variable, but b is destroyed after method ends
17+
++b;
18+
}
19+
20+
public static void main(String[] args) {
21+
StaticVariableDemo s = new StaticVariableDemo();
22+
23+
// ✅ First call to fun()
24+
// a = 10 → printed, then incremented to 11
25+
// b = 10 → printed, then dies after the method ends
26+
s.fun();
27+
28+
// ✅ Second call to fun()
29+
// a = 11 (static retains value) → printed, then incremented to 12
30+
// b = 10 (new local copy) → printed again, dies again
31+
s.fun();
32+
}
33+
}

Section10Methods/LocalandGlobalVariables/src/staticvariable.java

Lines changed: 0 additions & 13 deletions
This file was deleted.

0 commit comments

Comments
 (0)