Pass-by-value: a method gets a copy
16 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)When you call a method, Java copies each argument's value into the parameter. This is pass-by-value: the method works on a copy, never on your variable.
The method gets a copy
addBonus(marks) adds 5 inside the method, yet marks in main is still 70 afterwards. Java passes arguments by value: the parameter gets a copy of the value, like a photocopy of your marks card.
Example 1 · Changing the copy does not change the original
public class CopyDemo { public static void main(String[] args) { int marks = 70; addBonus(marks); System.out.println("In main after call: " + marks); }
static void addBonus(int marks) { marks = marks + 5; System.out.println("Inside method: " + marks); }}Inside method: 75 In main after call: 70
What this code does
- The call copies 70 into the parameter
marksofaddBonus, and that copy becomes 75. main'smarksis a different variable that only shares the name (Same name, two variables (opens in a new tab)), so it is still 70.
Keep the new value: return it
To keep the bonus, the method must hand the new value back. Return it, and store it in your own variable: marks = addBonus(marks);.
Example 2 · Return the new value and store it
public class ReturnDemo { public static void main(String[] args) { int marks = 70; marks = addBonus(marks); System.out.println("After bonus: " + marks); }
static int addBonus(int marks) { return marks + 5; }}After bonus: 75
What this code does
addBonusnow returns 75 instead of changing a copy that nobody sees.marks = addBonus(marks);stores the 75 back inmain's variable. Withoutmarks =, the 75 would be thrown away.
Why swap() cannot work
A swap(a, b) method swaps its two parameters, yet a and b in main stay the same. It swaps only the copies, and a return can send back just one value.
Trace the code
Watch the copies swap
Variables
- a
- 10
Output
(nothing printed yet)Line 3a starts at 10.
int, double, char and boolean. Arrays are passed by value too, but the value copied is a link to the data; Arrays and methods (opens in a new tab) shows what that changes.Next step
Check your understanding
7 quick questions