Java Reference
In-Depth Information
public static void tryElementChange(int[] num) {
// If array has at least one element, store 1116 in
// its first element
if (num != null && num.length > 0) {
num[0] = 1116;
}
}
public static void tryElementChange(String[] names) {
// If array has at least one element, store "Twinkle" in
// its first element
if (names != null && names.length > 0) {
names[0] = "Twinkle";
}
}
}
Before method call, origNum:[10, 89, 7]
Before method call, origNames:[Mike, John]
After method call, origNum:[1116, 89, 7]
After method call, origNames:[Twinkle, John]
Notice that first element of the arrays changed after the method calls. You can change the elements of an array
parameter inside a method, even if the array parameter is declared final .
The Object Referred by the Array Parameter Elements
This section applies to array parameters of only the reference type. If the array's reference type is mutable, you can
change the state of the object stored in the array elements. In the previous section, I discussed replacing the reference
stored in an array element by a new object reference. This section discusses changing the state of the object referred
to by the elements of the array. Consider an Item , as shown in Listing 15-7.
Listing 15-7. An Item Class
// Item.java
package com.jdojo.array;
public class Item {
private double price;
private String name;
public Item (String name, double initialPrice) {
this.name = name;
this.price = initialPrice;
}
public double getPrice() {
return this.price;
}
 
Search WWH ::




Custom Search