Java Reference
In-Depth Information
// Create and store a new int array in num
num = new int[]{10, 20};
System.out.println("Inside method-2:" + Arrays.toString(num));
}
}
Before method call:[101, 307, 78]
Inside method-1:[101, 307, 78]
Inside method-2:[10, 20]
After method call:[101, 307, 78]
If you do not want your method to change the array reference inside the method body, you must declare the
method parameter as final , like so:
public static void tryArrayChange( final int[] num) {
// An error. num is final and cannot be changed
num = new int[]{10, 20};
}
Elements of the Array Parameter
The values stored in the elements of an array parameter can always be changed inside a method. Listing 15-6
illustrates this.
Listing 15-6. Modifying Elements of an Array Parameter Inside a Method
// ModifyArrayElements.java
package com.jdojo.array;
import java.util.Arrays;
public class ModifyArrayElements {
public static void main(String[] args) {
int[] origNum = {10, 89, 7};
String[] origNames = {"Mike", "John"};
System.out.println("Before method call, origNum:" + Arrays.toString(origNum));
System.out.println("Before method call, origNames:" +
Arrays.toString(origNames));
// Call methods passing the arrays
tryElementChange(origNum);
tryElementChange(origNames);
System.out.println("After method call, origNum:" + Arrays.toString(origNum));
System.out.println("After method call, origNames:" +
Arrays.toString(origNames));
}
 
Search WWH ::




Custom Search