// DrJava saved history v2 // We started working with arrays today. int time []; // DECLARE an array reference variable time = new int[4]; // now CREATE the array - allow for four elements. // The position of an element in an array is indicated in the index. // The index of the first element is 0, so the last element is n-1, // if the array is size n. // The index is identified in square brackets [] following the // the arrray reference variable: time[0] // what is in the first element of the array // note that numbers in arrays are initialized to zero, and // objects are initialized to null. time[2] // what is in the third element of the array time[0] = 500; // ASSIGN a value to array element at index 0 time[2] = 200; time[3] = time[2]; time[5] time[4] time[3] int time2 [] = {1,2,3,4,5,6,7}; // you can declare the array and // insert the elements this way. int something[] = new something[1]; int something[] = new int[1]; // array of size 1 // In the following examples, we create arrays of BankAccount objects. // You may want to retrieve a copy of the BankAccount code to run these // statements. // here we declare and create an array of BankAccounts. BankAccount accts[] = new BankAccount[3]; accts[0] //Note that the BankAccount objects are null. accts[1] accts[2] // assign value to the reference accts[0], the first BankAccount accts[0] = new BankAccount("Angie",500.00); accts[1] = new BankAccount("Z", 200.00); accts[2] = new BankAccount("Alvina", 2000.0); // Or we could declare our array, and populate it with new // BankAccounts in a single statement. BankAccount acct[] = {new BankAccount("Angie",500.00), new BankAccount("Z", 200.00), new BankAccount("Alvina", 2000.0)}; // How would we access methods for the BankAccount objcts in our array? acct[0].getName() acct[2].getName() acct[1].getName() // to determine the length of our array we use the array variable length acct.length // We could use the length to control the number of iterations in our loop // as we access each element in our array. for (int i = 0; i < acct.length; i++) { System.out.println(acct[i].getName()); } // using the java code we created today: // look at numNulls BankAccount accts2[] = new BankAccount[3]; ArrayExamples.numNulls(accts2) accts2[2] = new BankAccount("Alvina", 2000.0); ArrayExamples.numNulls(accts2) // look at toCharArray char mychars[] = ArrayExamples.toCharArray("today is monday"); for (int i = 0; i < mychars.length; i++) { // what is in our array System.out.println(mychars[i]); } // look at printCharArray ArrayExamples.printCharArray(mychars)