/** * This program illustrates how to "expand" an array * Requires 3 steps: * 1. Create a new, larger array * 2. Use a loop to copy each element from the old to the new * 3. Assign the new array to the original array variable */ public class CopyArrayExample { public static void main(String [] args) { int [] orig = {4,9,-2}; // to copy an array, this doesn't do it! int [] copy = orig; // Here is what you have to do: // Instantiate new array copy = new int[6]; // Copy each element for(int i = 0; i < orig.length; i++) { copy[i] = orig[i]; } // Assign the new array memory address to the old array name // Java's garbage collector will take care of the old array space orig = copy; System.out.println("orig[5] = " + orig[5]); } }