Pass-by-Value Semantics in Java
What you'll learn: How Java actually passes data to methods — always by copying values, never by sharing the original variable itself.
The Core Rule: Java Always Copies
When you call a method in Java, the language always passes a copy of the value you provide. This is called pass-by-value. Java never gives a method direct access to your original variable.
For primitive types (like int, double, boolean), this means the method gets a copy of the number or value. Changes inside the method don't affect the original:
int x = 10;
changeValue(x);
// x is still 10
void changeValue(int num) {
num = 20; // only changes the copy
}
The Twist with Objects
For objects (like arrays or class instances), Java still passes by value — but here's the catch: the value being copied is the reference (the memory address pointing to the object), not the object itself.
Think of it like copying a house address on a piece of paper. You now have two pieces of paper with the same address. Using either paper, you can visit and modify the same house:
int[] numbers = {1, 2, 3};
modifyArray(numbers);
// numbers[0] is now 99!
void modifyArray(int[] arr) {
arr[0] = 99; // modifies the shared object
}
But if you reassign the parameter itself, only your copy of the address changes:
void replaceArray(int[] arr) {
arr = new int[]{7, 8, 9}; // only changes local reference
}
Key Takeaway: Java always passes copies of values. For primitives, you copy the actual data; for objects, you copy the reference, so both refer to the same object in memory, but you can't change what the original variable points to.