Why Java Can't Swap Primitive Values Inside a Method – The Correct Way
This article explains that Java passes primitive arguments by value, so attempts to swap two ints inside a method have no effect on the caller, and demonstrates both the faulty implementation and the proper solutions using a temporary variable or a return value.
When you pass an object (or primitive) as a parameter to a Java method, the method receives only a copy of the value. Modifying that copy does not change the original variable in the caller's scope. The article illustrates this with a simple int‑swap example.
Faulty implementation
int a = 1, b = 2;
output("a:" + a, "b:" + b);
changeNum(a, b);
output("a:" + a, "b:" + b); public void changeNum(int a, int b) {
int i = a;
a = b;
b = i;
}The console output shows that the values of a and b remain unchanged after the method call:
Before call: a:1 b:2
After call: a:1 b:2Correct implementation using a temporary variable
int a = 1, b = 2;
output("a:" + a, "b:" + b);
int i = a;
a = b;
b = i;
output("a:" + a, "b:" + b);Now the output correctly shows the values swapped:
Before swap: a:1 b:2
After swap: a:2 b:1Correct implementation using a return value
public int[] changeNum(int a, int b) {
int[] abc = { b, a };
return abc;
} int a = 1, b = 2;
output("a:" + a, "b:" + b);
int[] abc = changeNum(a, b);
a = abc[0];
b = abc[1];
output("a:" + a, "b:" + b);This version returns an array containing the swapped values, which the caller then assigns back to a and b, achieving the desired effect.
The key takeaway is that any method that needs to modify primitive data must either operate on a mutable wrapper object or return the new values, because Java's pass‑by‑value semantics prevent direct modification of the caller's primitives.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
