Commit e5bde3e
committed
feat: Add MethodAB2 to demonstrate call by value in Java parameter passing
WHAT the code does:
Defines a MethodAB2 class with a static inc(int x) method.
inc() increments its parameter and prints the incremented value.
main() calls inc(a) with a = 10, then prints a again to show that its original value remains unchanged.
WHY this matters:
Illustrates Java’s call by value semantics:
- Primitive values are copied into method parameters
- Changes inside the method do not affect the original variable
Highlights the difference between mutating local copies vs persistent changes in caller scope.
Provides clarity on a common interview question and beginner confusion point.
HOW it works:
main() declares two integers, a = 10 and b = 15 (b is unused here).
Calls inc(a):
- Inside inc(), x is incremented to 11 and printed
- Outside, a remains 10 since only a copy was modified
Demonstrates immutability of primitive arguments in method calls.
Tips and gotchas:
For primitives, changes inside a method never reflect back to the caller.
For objects, references are passed by value, but methods can mutate the object’s internal state.
This distinction is crucial: arrays, lists, and objects behave differently from primitives.
Avoid relying on side effects when working with primitives in helper methods; return the new value instead.
Use-cases:
Educational demonstration for call by value in Java.
Foundation for understanding method behavior with primitives vs objects.
Useful for explaining why wrapper classes or mutable containers (e.g., AtomicInteger) are used to simulate reference-like behavior.
Short key: class-methodab2 call-by-value primitive-parameter.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent cbf1444 commit e5bde3e
1 file changed
+3
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
| 2 | + | |
4 | 3 | | |
5 | 4 | | |
6 | 5 | | |
7 | 6 | | |
8 | 7 | | |
9 | | - | |
| 8 | + | |
10 | 9 | | |
11 | 10 | | |
12 | | - | |
| 11 | + | |
0 commit comments