Pass as argument - a copy of the reference to the instantiated array is passed to the method. This means that any changes made to the array elements inside the method are persistent. The one exception to this is if you assign the argument to reference a different array in memory.
public class ArrayParms {
public static int[] arrMethod (int[] arrOne, Person[] arrObj) {
int [] temp = {6, 7, 8, 9, 10};
System.out.println("Inside method arrMethod:");
System.out.println("arrOne is " + printIntArr(arrOne));
System.out.println("temp is " + printIntArr(temp));
System.out.println("arrObj is " + printObjArr(arrObj));
// change values
for (int i = 0; i < arrOne.length; i++) {
arrOne[i] += 1;
}
arrObj[0].setName("Juan Valdez");
arrObj[0].setId(362);
arrObj[2] = new Person("Mary Smith", 548);
System.out.println("At end of method arrMethod:");
System.out.println("arrOne is " + printIntArr(arrOne));
System.out.println("temp is " + printIntArr(temp));
System.out.println("arrObj is " + printObjArr(arrObj));
return temp;
}
public static void main(String[] args) {
int [] one = {0, 1, 2, 3, 4, 5};
int [] two = new int[2];
Person [] gamma = new Person[3];
gamma[0] = new Person("Maria Santos", 156);
gamma[1] = new Person("Caiji Zheng", 742);
System.out.println("Before method call:");
System.out.println("one is " + printIntArr(one));
System.out.println("two is " + printIntArr(two));
System.out.println("gamma is " + printObjArr(gamma));
two = arrMethod(one, gamma);
System.out.println("After method call:");
System.out.println("one is " + printIntArr(one));
System.out.println("two is " + printIntArr(two));
System.out.println("gamma is " + printObjArr(gamma));
}
public static String printIntArr(int[] arr) {
String result = "";
for (int o : arr) {
result += o;
result += " ";
}
return result;
}
public static String printObjArr(Object[] arr) {
String result = "";
for (Object o : arr) {
result += o;
result += " ";
}
return result;
}
}
ExercisesExercises
1.
Q30: Select the correct output produced by this code:
System.out.print("Before method call:");
System.out.print(" one is " + printIntArr(one));
System.out.print(" two is " + printIntArr(two));
System.out.print(" gamma is " + printObjArr(gamma));
After method call:
one is 1 2 3 4 5 6
two is 7 8 9 10
gamma is Person{name='Juan Valdez', id=362} Person{name='Caiji Zheng', id=742} Person{name='Mary Smith', id=548}
After method call:
one is 1 2 3 4 5 6
two is 6 7 8 9 10
gamma is Person{name='Maria Santos', id=156} Person{name='Caiji Zheng', id=742} Person{name='Mary Smith', id=548}
After method call:
one is 1 2 3 4 5 6
two is 0 0
gamma is Person{name='Juan Valdez', id=362} Person{name='Caiji Zheng', id=742} Person{name='Mary Smith', id=548}
After method call:
one is 1 2 3 4 5 6
two is 6 7 8 9 10
gamma is Person{name='Juan Valdez', id=362} Person{name='Caiji Zheng', id=742} Person{name='Mary Smith', id=548}