0

Newbie question. Trying to get my head around reference vs value arguments in Java, consider the following:

//Helper function int[] to csv    
public static String csv(int[] values){
    String ret = "";
    for(int i = 0; i < values.length; i++)
        ret = String.format("%s%s%s",ret,i == 0 ? "" : ", ",values[i]);
    return ret;
}

//Helper function, print to console
public static void print(int[] v){
    System.out.println(csv(v));
}



public static void method1(int[] input){
    input[0] = 3; input[1] = 4; input[2] = 5;
}

public static void method2(int[] input){
    input = new int[]{6,7,8};
}

public static void main(String[] args) throws Exception {
    int[] original = {0,1,2};
    print(original);

    method1(original);
    print(original);   //As expected

    method2(original);
    print(original);   //Modification ignored
}

In the above, changes to the array in method 1 are stored, but in method 2, the new assignment inside the function does not affect the original array and therefore has local scope.

So what if for example I need to do an array resize operation on an array passed by reference? is this not possible in java?

Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88

1 Answers1

2

All parameters in Java are passed by copy. The question is, copy of what? In the case of objects, including arrays, the object reference is copied. You now have two references to the same object, so the object can be modified.

In method2, the parameter "input" is initially set to the object reference to the array. You then modify "input" to point to another array. That has no impact on the caller. If you had left "input" alone and used it to change the elements, then you would have seen the change in the caller.

Steve11235
  • 2,849
  • 1
  • 17
  • 18