Skip to content

Commit e5bde3e

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

File tree

1 file changed

+3
-4
lines changed

1 file changed

+3
-4
lines changed
Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
public class MethodAB2 {
2-
static void inc(int x)
3-
{
2+
static void inc(int x) {
43
x++;
54
System.out.println(x);
65
}
76
public static void main(String[] args) {
87
int a=10,b=15;
9-
inc(a); //Paramter passing. the value of actual parameter will not modify if the formal parameter will change.
8+
inc(a); //Parameter passing. the value of actual parameter will not modify if the formal parameter will change.
109
System.out.println(a); //Call by value
1110
}
12-
}
11+
}

0 commit comments

Comments
 (0)