Passing arrays as arguments

This is a misunderstanding – there is a subtle but important distinction. Arrays are objects. Java passes a value – and that value is a reference to the object. For discussion, see for example:

The important thing to understand here is that arrays like float[], Processing objects like PVector, Java objects like HashMap and your own custom objects class MyObject all follow the same rules. You pass in a value that is a reference, which you can use to access and update the object, but you cannot manipulate it as a reference – it is just a value.

A classic example of the consequences of this is badSwap(). If Java was pass by reference, badSwap() would swap the references – but it isn’t, so it can’t, and it doesn’t.

Java does manipulate objects by reference, and all object variables are references. However, Java doesn’t pass method arguments by reference; it passes them by value. https://www.javaworld.com/article/2077424/learn-java/learn-java-does-java-pass-by-reference-or-pass-by-value.html

Take the badSwap() method for example:

public void badSwap(int var1, int var2)
{
  int temp = var1;
  var1 = var2;
  var2 = temp;
}

For arrays / objects, try this:

void setup(){
  float[] vars1 = new float[]{1.0, 2.0};
  float[] vars2 = new float[]{3.0, 4.0};
  badSwap(vars1, vars2);
  println("global results:");
  println(vars1);
  println(vars2);
}

public void badSwap(float[] vars1, float[] vars2) {
  println("args:\n", vars1, vars2); // yep, those are reference values
  // we can use them to update the referenced objects
  vars1[0] = 100;
  // ...but we can't manipulate global references, because we only have their values
  // we swap the values locally
  float[] temp = vars1;
  vars1 = vars2;
  vars2 = temp;
  // ...but they aren't references, so that had no effect on the global objects
  println("new local values:\n", vars1, vars2);
  // and this won't do anything globally either -- these are just local values:
  vars1 = null;
  vars2 = null;
  println("new local values:\n", vars1, vars2);
}
3 Likes