



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to arrays in java, a fixed-sized collection of variables of the same type with a single identifier. Topics covered include array declaration, initialization, accessing elements, assigning values, and using arrays with loops. Examples are given for numeric, boolean, and reference types.
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!




Announcements Read Section 4.12 again! Next Program on course web site! Quiz Review Arrays A few days ago I said that Java provided two ways of keeping a set of values in a collection:
quizScores = new int[ 18 ]; temperature = new double[ 365 ]; monthNames = new String[ 12 ]; daysPerMonth = new String[ 12 ]; classList = new Student[ numStudents ]; Draw picture of one or two of these. Show what happens to the array elements. numeric types initialized to 0 Booleans initialized to false References initialized to null โ means that they donโt reference anything yet. Can also do both parts in a single declaration Emphasize that declaring the array only creates the reference. You have to allocate the array elements also! Accessing array elements Ok, this is all great. I've created these arrays that are sets of variables with the same name. How do I actually use the array elements in a program? We access the array elements using subscripting or indexing. Each array element has a subscript (or index ) that we can use to refer to that element. The subscripts are integer values, starting at 0. Thus, the first element of the array has subscript 0, the second has subscript 1, and the last has a subscript of the array-size - 1. [Note similarity to indexing in ArrayList]. int[] daysPerMonth = new int[12]; Draw picture, showing the array subscripts, and the names of each element (daysPerMonth[0], daysPerMonth[1], ...) The elements of an array are referenced using the array name and a subscript. So, we can say daysPerMonth[6] or quizScores[4] or temperature[300]. The value of the index or subscript MUST BE an integer expression. That means we don't have to use constants. temperature[ index ] daysPerMonth[ currentMonth ] Assigning values to array elements Use an assignment statement, but the variable on the left-hand side is indexed. monthName[0] = "January"; daysPerMonth[0] = 31; // January (1 - 1)
size method:
Lab Exercise Complete the ArrayExample class. It has two methods that you need to finish: