2

When I passing an object reference (arrays are objects) to a method, the value is passed, right?

In the following code the initial value is: 333. After method passing, the value is changed. Why? Is in this case the reference passed instead the value?

Are arrays "special cases"?

public static void main(String[] args) {
    int[] myArray = { 333 };
    valueOrRef(myArray);            // Value or Reference?
    System.out.println(myArray[0]); // 777 (changed)
}

public static void valueOrRef(int[] myArgument) {
    myArgument[0] = 777;
}

Another approach: (the logic "pass by value"):

public static void main(String[] args) {
    int[] myArray = { 333 };
    valueOrRef(myArray[0]);         // Value or Reference?
    System.out.println(myArray[0]); // 333 (after method still unchanged)
}

public static void valueOrRef(int myArray2) {
    myArray2 *= 2;
}
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    A reference to the array is passed. But this references is passes by-value. – Christian Tapia Feb 16 '15 at 15:38
  • The question that this was closed as a duplicate of addresses this issue on a more general level and not on arrays specifically. In addition to the answer provided there, one has to realize that an array is an object, and that an initialization expression such as `{ 333 }` puts the array on the heap. – aioobe Feb 16 '15 at 15:44

1 Answers1

3

The value is always passed, but keep in mind that for arrays the value is in fact a reference to an array and not the array itself.

The first valueOrRef method changes the content of the array pointed at by myArgument which is why you see the effect on the array after calling the method.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    Everything in Java is passed by value. Java has no pass by reference (object references, including array references, are passed by value.) – Brian Goetz Feb 16 '15 at 15:39