ArraysA problem with simple variablesMultiple valuesIndexing into arraysUsing array elementsArray valuesStrings and arraysDeclaration versus definitionDeclaring and defining arraysTwo ways to declare arraysArray assignmentAn array’s size is not part of its typeSlide 13Length of an arrayStepping through an arrayExample of array use IExample of array use IIExample of array use IIIArray namesMagic numbersNullPointerExceptionArrays of objectsInitializing arrays IInitializing arrays IIArray literalsInitializing arrays IIIArrays of arraysExample array of arraysSize of 2D arraysThe EndJan 14, 2019Arrays2A problem with simple variablesOne variable holds one valueThe value may change over time, but at any given time, a variable holds a single valueIf you want to keep track of many values, you need many variablesAll of these variables need to have namesWhat if you need to keep track of hundreds or thousands of values?3Multiple valuesAn array lets you associate one name with a fixed (but possibly large) number of valuesAll values must have the same typeThe values are distinguished by a numerical index between 0 and array size minus 112 43 6 83 14 -57 109 12 0 6 0 1 2 3 4 5 6 7 8 9myArray4Indexing into arraysTo reference a single array element, use array-name [ index ]Indexed elements can be used just like simple variablesYou can access their valuesYou can modify their valuesAn array index is sometimes called a subscript12 43 6 83 14 -57 109 12 0 6 0 1 2 3 4 5 6 7 8 9myArraymyArray[0]myArray[5]myArray[9]5Using array elementsExamples:• x = myArray[1]; // sets x to 43• myArray[4] = 99; // replaces 14 with 99• m = 5; y = myArray[m]; // sets y to -57• z = myArray[myArray[9]]; // sets z to 10912 43 6 83 14 -57 109 12 0 6 0 1 2 3 4 5 6 7 8 9myArray6Array valuesAn array may hold any type of valueAll values in an array must be the same typeFor example, you can have:an array of integers (ints)an array of Stringsan array of PersonIn this case, all the elements are Persons; but they may belong to different subclasses of PersonFor example, if you have a class Employee extends Person, then you can put Employees in your array of PersonThis is because an Employee is a PersonYou can even have arrays of arrays, for example, an array of arrays of int7Strings and arraysStrings and arrays both have special syntaxStrings are objects, and can be used as objectsArrays are objects, butArrays are created using special syntax:new type[size] instead of new Person()If an array holds elements of type T, then the array’s type is “array of T”8Declaration versus definitionArrays are objectsCreating arrays is like creating other objects:the declaration provides type information and allocates space for a reference to the array (when it is created)the new definition actually allocates space for the arraydeclaration and definition may be separate or combinedExample for ordinary objects: Person p; // declaration p = new Person("John"); // definition Person p = new Person("John"); // combined9Declaring and defining arraysExample for array objects:int[ ] myArray; // declarationThis declares myArray to be an array of integersIt does not create an array—it only provides a place to put an arrayNotice that the size is not part of the typemyArray = new int[10]; // definitionnew int[10] creates the arrayThe rest is an ordinary assignment statementint[ ] myArray = new int[10]; // both10Two ways to declare arraysYou can declare more than one variable in the same declaration: int a[ ], b, c[ ], d; // notice position of bracketsa and c are int arraysb and d are just intsAnother syntax: int [ ] a, b, c, d; // notice position of bracketsa, b, c and d are int arrays When the brackets come before the first variable, they apply to all variables in the listBut...In Java, we typically declare each variable separately11Array assignmentArray assignment is object assignmentObject assignment does not copy values Person p1; Person p2; p1 = new Person("John"); p2 = p1; // p1 and p2 refer to the same personArray assignment does not copy values int[ ] a1; int[ ] a2; a1 = new int[10]; a2 = a1; // a1 and a2 refer to the same array12An array’s size is not part of its typeWhen you declare an array, you declare its type; you must not specify its sizeExample: String names[ ];When you define the array, you allocate space; you must specify its sizeExample: names = new String[50];This is true even when the two are combinedExample: String names[ ] = new String[50];13Array assignmentWhen you assign an array value to an array variable, the types must be compatibleThe following is not legal: double[ ] dub = new int[10]; // illegalThe following is legal: int[ ] myArray = new int[10];...and later in the program, myArray = new int[500]; // legal!This is legal because the array’s size is not part of its type, but part of its value14Length of an arrayArrays are objectsEvery array has an instance constant, length, that tells how large the array isExample: for (int i = 0; i < scores.length; i++) System.out.println(scores[i]);Use of length is always preferred over using a constant such as 10Arrays have a length variable, Strings have a length() method15Stepping through an arrayThe for loop is ideal for visiting every value in an arrayThe form is: for (int i = 0; i < myArray.length; i++) {...}Example: for (int i = 0; i < students.length; i++) { System.out.println(students[i].name); }In general we like to use meaningful names for variables, but in this case, the name i is traditional, and betteri is instantly recognizable as the index of an enclosing for loopInner (nested) loops should use j, then k (then, if necessary, m, then n, but not l– do you see why?)You should avoid deeply nested loops—three is deep enough!It’s usually best to declare i right in the for statement itselfi++ means “add 1 to i”16Example of array use ISuppose you want to find the largest value in an array scores of 10 integers: int largestScore = 0; for (int i = 0; i < 10; i++) { if (scores[i] > largestScore) { largestScore = scores[i]; } }Would this code work if
View Full Document