Commit 678da37
committed
feat: Add ObjectPassingAB3 to demonstrate mutability via arrays for primitive-like updates
WHAT the code does:
Defines ObjectPassingAB3 with two static methods:
- change(int[] A, int index, int value) updates a specific element in an integer array.
- change2(int[] x, int value) modifies the first element of an integer array (simulating primitive reassignment).
In main():
- Creates an array A = {2, 4, 6, 8, 10}, calls change(A, 2, 20), and prints the updated result → 2 4 20 8 10.
- Wraps a primitive value inside an array x = {10}, calls change2(x, 20), and prints the updated first element → 20.
WHY this matters:
Shows how arrays (mutable objects) can be used to simulate pass-by-reference behavior for primitives.
Highlights the contrast with Java’s call-by-value semantics:
❌ Primitives passed directly cannot be modified inside methods.
📌 Wrapping a primitive in an array allows methods to mutate the underlying value, because the array reference points to shared mutable data.
Demonstrates a workaround for situations where primitive-like values need to be updated through method calls.
HOW it works:
change(A, 2, 20) mutates A’s third element. Since arrays are passed by reference copy, the change persists in main().
change2(x, 20) mutates x[0]. Since x points to the same array in both caller and method, the updated value is visible in main().
Outputs confirm persistent updates:
Array: 2 4 20 8 10
Wrapped primitive: 20.
Tips and gotchas:
This pattern works because arrays are mutable objects; the reference copy passed to methods allows shared modification.
While effective, this approach may reduce clarity compared to returning a value.
For safer design, prefer wrapper classes (e.g., AtomicInteger) or immutable/functional patterns that return new values.
Use array-wrapping sparingly; it’s more of an educational trick than a production-grade solution.
Use-cases:
Educational demo of pass-by-value vs reference-copy semantics in Java.
Useful in scenarios where primitive updates need to persist across method calls.
Foundation for explaining why mutable wrappers exist in concurrent and functional programming.
Short key: class-objectpassingab3 array-wrapper simulate-pass-by-reference.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5c00e22 commit 678da37
File tree
2 files changed
+22
-16
lines changed- Section10Methods/src
2 files changed
+22
-16
lines changed| 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 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
This file was deleted.
0 commit comments