Skip to lesson

Pass-by-value: a method gets a copy

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.

main has marks = 70. The call addBonus(marks) copies 70 into the parameter of addBonus, and the copy becomes 75. main's marks is untouched and still 70; the copy is thrown away when the method ends.

Example 1 · Changing the copy does not change the original

CopyDemo.javaJava
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);    }}
Output
Inside method: 75
In main after call: 70

What this code does

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

ReturnDemo.javaJava
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;    }}
Output
After bonus: 75

What this code does

  • addBonus now returns 75 instead of changing a copy that nobody sees.
  • marks = addBonus(marks); stores the 75 back in main's variable. Without marks =, 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

public class SwapTry {
public static void main(String[] args) {
int a = 10;
int b = 20;
swap(a, b);
System.out.println("a = " + a + ", b = " + b);
}
static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
}

Variables

a
10

Output

(nothing printed yet)

Line 3a starts at 10.

Step 1 of 9
This lesson is about simple types like 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