Skip to content

Commit 96e1607

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

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

Section10Methods/Methods 2.O/src/Swap.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,21 @@ public static void main(String[] args) {
44
int b = 20;
55

66
// swap numbers code
7-
// int temp = a;
8-
// a = b;
9-
// b = temp;
7+
// int temp = a;
8+
// a = b;
9+
// b = temp;
1010

1111
swap(a, b);
12-
1312
System.out.println(a + " " + b);
1413

15-
String name = "Kunal Kushwaha";
14+
String name = "Swapping numbers";
1615
changeName(name);
1716
System.out.println(name);
1817
}
1918

2019
static void changeName(String naam) {
21-
naam = "Rahul Rana"; // creating a new object
20+
naam = "Why name doesn’t change when we called this method inside main method." +
21+
"you will get answer in the next code.";
2222
}
2323

2424
static void swap(int num1, int num2) {

0 commit comments

Comments
 (0)