Skip to content

Commit 28d7664

Browse files
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

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public class StrongReferenceDemo {
2+
public static void main(String[] args) {
3+
// Create a strong reference to a Phone object.
4+
Phone phone = new Phone("Apple", "16 Pro Max");
5+
6+
// At this point, 'phone' strongly refers to the Phone object in heap.
7+
System.out.println("Phone via strong reference: " + phone);
8+
9+
// Nullify the reference, making the object eligible for GC.
10+
phone = null;
11+
12+
// Now the Phone object has no references → eligible for GC.
13+
System.out.println("After nullifying reference: " + phone);
14+
}
15+
}
16+
17+
// Demonstrates how strong references work in Java.
18+
// A strong reference prevents an object from being garbage collected
19+
// until the reference is explicitly set to null or goes out of scope.

0 commit comments

Comments
 (0)