Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Exploring the Java Collection Framework Using ArrayLists

Siu KWAN Yuen
PLUS
Siu KWAN Yuen
Courses Plus Student 2,898 Points

Help! pass by value or pass by reference?

Is java pass by value or by reference. I think reference makes much more sense but I have heard people in the Stack Overflow saying that java is a language that passes by value.

1 Answer

Java only has pass by value. Any value you pass into a method as an argument is copied shallowly. This means the following code does not work as you might expect at first glance:

//...
    int a = 0;
    int b = 1;
    swap(a, b);
// ...

private void swap(int x, int y) {
    int t = x;
    x = y;
    y = t;
}

Even if a and b were objects, i. e. references, swap still would not work. However, since we only perform a shallow copy, if a method manipulates a property of an object, it will propagate outside. So by using objects (references) with call by value, we can simulate the call by reference behavior.

The main question, you should ask yourself is this: What if I assign directly to a parameter? Does this also change values in other parts of the code? If it does, it's pass by reference. If it does not, it's pass by value. Again, in Java such an assignment never has an effect outside the method. So it's call by value.