Commit 52fbb53
committed
feat: Add SwapAnswer class showing mutable array swap and String reassignment
WHAT the code does:
- Defines a `SwapAnswer` class demonstrating how to make swaps and updates persist.
- Uses an **array** to swap integers:
- `swap(int[] arr)` exchanges `arr[0]` and `arr[1]`.
- Works because arrays are mutable objects in Java.
- For Strings:
- `changeName(String naam)` returns a new string.
- Caller explicitly reassigns `name` to the return value, making the change visible.
WHY this matters:
- Shows how to overcome Java’s **pass-by-value** semantics:
- Mutable objects (like arrays) allow persistent modifications.
- Immutable objects (like Strings) require reassignment.
- Reinforces concepts of **mutability vs immutability** in Java.
HOW it works:
1. Array `{10, 20}` passed to `swap()`.
- After swap → `{20, 10}`.
- Printing shows `"20 10"`.
2. String `"Swapping numbers"` passed to `changeName()`.
- Returns new string.
- Caller assigns it back to `name`.
- Printing shows updated string message.
Tips & gotchas:
- Arrays provide mutability, but introducing a custom wrapper class could make swaps clearer.
- For Strings, since they are immutable, always return a new value if modification is required.
- Be mindful of side effects: changing arrays inside methods alters caller’s copy too.
- Demonstrates a common interview pitfall: difference between reassigning a reference and mutating an object.
Use-cases:
- Educational example on **mutability and method behavior**.
- Foundation for explaining why wrapper objects (like `AtomicInteger`) are used for pass-by-reference-like behavior.
- Practical in cases where modifications must reflect outside method scope.
- Useful exercise for distinguishing **Java immutability (String)** from **mutability (array)**.
Short key: class-swap answer-array-mutable-string-reassign.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 96e1607 commit 52fbb53
1 file changed
+48
-0
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 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
0 commit comments