Commit 5c00e22
committed
feat: Add ObjectPassingAB2 to contrast array mutation with primitive immutability in method calls
WHAT the code does:
Defines ObjectPassingAB2 with two static methods:
- change(int[] A, int index, int value) updates an array element at the specified index.
- change2(int x, int value) assigns a new value to a primitive parameter, but only within the method scope.
In main():
- Creates an array A = {2, 4, 6, 8, 10}.
- Calls change(A, 2, 20) to update the third element from 6 to 20.
- Prints the updated array using an enhanced for loop.
- Declares primitive x = 10, calls change2(x, 20), and prints the result to show the original x remains unchanged.
WHY this matters:
Demonstrates Java’s pass-by-value semantics:
- For arrays and objects, a reference copy is passed. Mutations affect the original object.
- For primitives, only the raw value is passed. Reassignments inside the method affect only the local copy.
Clarifies why Java is always “pass-by-value,” though outcomes differ for mutable vs immutable types.
HOW it works:
change(A, 2, 20) updates A[2] to 20. Printed result: 2 4 20 8 10.
change2(x, 20) updates only the local copy of x inside the method. The original x in main remains 10.
This demonstrates:
❌ Primitives cannot be changed inside methods, since only a value copy is passed.
📌 Arrays/objects → pass reference copy → can modify original.
📌 Primitives → pass value copy → original stays unchanged.
Tips and gotchas:
Be explicit about side effects when writing methods that mutate inputs, especially arrays or collections.
For primitives, return the updated value if persistence outside the method is required.
This distinction is critical in API design, where immutability and predictability matter.
To avoid surprises, prefer functional-style programming where methods return new results rather than mutating inputs.
Use-cases:
Educational demonstration of Java parameter passing differences.
Helps explain why wrapper classes like AtomicInteger exist to emulate reference-like behavior for primitives.
Practical foundation for teaching defensive programming and immutability.
Short key: class-objectpassingab2 array-mutation primitive-call-by-value.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent a4c46da commit 5c00e22
1 file changed
+6
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
| 2 | + | |
4 | 3 | | |
5 | 4 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 5 | + | |
9 | 6 | | |
10 | 7 | | |
11 | | - | |
12 | | - | |
13 | | - | |
| 8 | + | |
14 | 9 | | |
15 | 10 | | |
16 | 11 | | |
17 | 12 | | |
18 | | - | |
19 | | - | |
20 | | - | |
| 13 | + | |
| 14 | + | |
21 | 15 | | |
22 | 16 | | |
| 17 | + | |
23 | 18 | | |
24 | | - | |
25 | 19 | | |
26 | | - | |
27 | 20 | | |
28 | 21 | | |
29 | 22 | | |
0 commit comments