Java examples for Object Oriented Design:Method Parameter
Modifying Elements of an Array Parameter Inside a Method
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] origNum = {1, 2, 3}; 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);/*from w w w . ja v a2s .c o m*/ tryElementChange(origNames); System.out.println("After method call, origNum:" + Arrays.toString(origNum)); System.out.println("After method call, origNames:" + Arrays.toString(origNames)); } 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] = 6; } } public static void tryElementChange(String[] names) { if (names != null && names.length > 0) { names[0] = "new"; } } }