Commit 28d7664
committed
feat(StrongReferenceDemo): add demo of strong references and GC eligibility
What
- Added `StrongReferenceDemo` class.
- Created `Phone` object with strong reference.
- Printed object when strongly referenced.
- Set reference to null and printed again.
Why
- To demonstrate how strong references work in Java.
- Show that as long as a strong reference exists, the object is not garbage collected.
- Illustrate that nullifying the reference makes the object eligible for GC.
How
- Step 1: Create strong reference `phone` → new Phone("Apple", "16 Pro Max").
- Step 2: Print object via strong reference.
- Step 3: Nullify reference (`phone = null`).
- Step 4: Print reference again (shows null).
- Garbage collector can now reclaim the object since no strong references exist.
Logic
- Inputs:
- Phone constructor with brand and model.
- Outputs:
- Console logs showing object before and after nullifying reference.
- Flow:
1. Allocate Phone on heap.
2. Reference with strong variable.
3. Print reference.
4. Set to null, making object unreachable.
- Constraints:
- Actual GC execution is JVM-dependent and not forced by this demo.
- Complexity:
- O(1) for reference assignment and printing.
Real-life applications
- Strong references are the default in Java.
- Used for normal object handling in applications.
- Important to nullify or let references go out of scope to allow GC in long-lived structures.
Notes
- Strong reference = default reference type in Java.
- Objects with strong refs are **never** collected by GC.
- To allow collection, references must be explicitly cleared or go out of scope.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent deaabf0 commit 28d7664
File tree
1 file changed
+19
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Garbage Collection/src
1 file changed
+19
-0
lines changedLines changed: 19 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
0 commit comments