Commit 96e1607
committed
feat: Add Swap class to demonstrate Java parameter passing and immutability
WHAT the code does:
- Defines a `Swap` class to illustrate why swapping and string modification don’t persist outside methods in Java.
- In `main()`:
- Declares integers `a = 10`, `b = 20`.
- Calls `swap(a, b)` → attempts to swap numbers.
- Prints `a` and `b` → still `10 20` because Java is **pass-by-value**.
- Declares string `name = "Swapping numbers"`.
- Calls `changeName(name)` → attempts to reassign.
- Prints `name` → still `"Swapping numbers"` because strings are **immutable** and reassignment doesn’t affect the caller.
WHY this matters:
- Demonstrates **pass-by-value** semantics in Java.
- Shows difference between reassigning parameters vs modifying objects.
- Highlights **immutability of String** in Java.
HOW it works:
1. `swap(int num1, int num2)`:
- Swaps locally inside the method.
- Original `a` and `b` remain unchanged.
2. `changeName(String naam)`:
- Reassigns `naam` to a new string.
- Caller’s reference (`name`) is unaffected.
3. Output:
- `"10 20"` for numbers.
- `"Swapping numbers"` for string.
Tips & gotchas:
- To persist swapping, use a wrapper class or return swapped values.
- For mutable objects (e.g., arrays), modifications inside methods *will* persist.
- Strings behave differently because they are immutable objects.
- Demonstrates why Java is sometimes confusingly described as “pass-by-value of the reference”.
Use-cases:
- Educational example for **Java parameter passing rules**.
- Interview discussion starter on **immutability and pass-by-value**.
- Foundation for understanding behavior of mutable vs immutable objects.
- Leads into learning about wrapper classes or data structures for swapping.
Short key: class-swap-pass by value-immutability.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent fe97b75 commit 96e1607
1 file changed
+6
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
7 | | - | |
8 | | - | |
9 | | - | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
10 | 10 | | |
11 | 11 | | |
12 | | - | |
13 | 12 | | |
14 | 13 | | |
15 | | - | |
| 14 | + | |
16 | 15 | | |
17 | 16 | | |
18 | 17 | | |
19 | 18 | | |
20 | 19 | | |
21 | | - | |
| 20 | + | |
| 21 | + | |
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
| |||
0 commit comments