Title: Arrays
1Arrays
Mr. Smith AP Computer Science A
2Conceptual Overview
- An array consists of an ordered collection of
similar items. - An array has a single name, and the items in an
array are referred to in terms of their position
within the array. - An array makes it just as easy to manipulate a
million test scores as it would to work with
three test scores.
Java Concepts 7.1 (Arrays)
3Conceptual Overview
- The items in an array are called elements.
- For any particular array, all the elements must
be of the same type. - The type can be any primitive, String, or object
data type. - For instance, we can have an array of test
scores, an array of names, or even an array of
Student objects.
Java Concepts 7.1 (Arrays)
4Conceptual Overview
- Each array below contains five elements (they
each have a length of 5). The first element in
the array named test is referred to as test0,
the second as test1, and so on. - An item's position within an array is called its
index, subscript, or position (all these terms
mean the same thing).
Java Concepts 7.1 (Arrays)
5Simple Array Manipulations
- First lets declare and instantiate an array of
500 integer values. - By default, all of the values are initialized to
0.
int abc new int500
Java Concepts 7.1 (Arrays)
6Simple Array Manipulations
- The basic syntax for referring to an array
element has the form - Where ltindexgt must be between 0 and (the array's
length minus 1). - The subscript operator ( ) has the same
precedence as the method selector (.).
ltarray namegt ltindexgt i.e. testScore3
Java Concepts 7.1 (Arrays)
7Simple Array Manipulations
- For example we assign values to the first five
elements - When assigning a value to the 500th element, we
must remember that its index is 499, not 500
int i 3 abc0 78 //1st
element 78 abc1 66 //2nd
element 66 abc2 (abc0 abc1) / 2 //3rd
element average of first two abci 82
//4th element 82 because i is 3 abci
1 94 //5th element 94
because i 1 is 4
abc499 76 //500th element
76
Java Concepts 7.1 (Arrays)
8Simple Array Manipulations
- The JVM checks the values of subscripts before
using them and throws an ArrayIndexOutOfBoundsExce
ption if they are out of bounds (less than 0 or
greater than the array length - 1). - The detection of a range bound error is similar
to the JVM's behavior when a program attempts to
divide by 0.
Java Concepts 7.1 (Arrays)
9Simple Array Manipulations
- We frequently need to know an array's length.
- The array itself makes this information available
by means of a public instance variable called
length
System.out.println ("The size of abc is "
abc.length)
Java Concepts 7.1 (Arrays)
10Looping Through Arrays
- Sum the Elements
- Team up with a partner if youd like
- Write a loop that will sum all the elements in
array abc - In 5 minutes we will discuss how to do this
Java Concepts 7.1 (Arrays)
11Looping Through Arrays
- Sum the Elements
- Each time through the loop adds a different
element to the sum. On the first iteration we add
abc0 and on the last abc499.
int sum 0 for (int i 0 i lt abc.length
i) sum abci
If using an enhanced for loop (we will discuss
this later)
int sum 0 for (int element abc) //
enhanced for loop sum element
Java Concepts 7.1 (Arrays)
12New to Java 5.0
- Enhanced for loop
- a.k.a for each loop
Java Concepts 7.4 (The Enhanced for Loop)
13Enhanced for Loop
- This type of loop visits each element in an array
from the first position to the last position. - On each pass through the loop, the element at the
current position is automatically assigned to a
temporary variable. No other loop control
information is required.
Java Concepts 7.4 (The Enhanced for Loop)
14Enhanced for Loop
- The syntax is much simpler than the standard for
loop - for (lttemp variable declarationgt ltarray
objectgt) ltstatementgt - The type of the temporary variable must be
compatible with the element type of the array.
Printing all elements in an array using a
Standard for loop for (int i 0 i lt
abc.length i) System.out.print(
abci )
Printing all elements in an array using an
Enhanced for loop for (int abcElement abc )
System.out.print( abcElement )
Java Concepts 7.4 (The Enhanced for Loop)
15Enhanced for Loop
- An enhanced for loop is clearly simpler to write
than a standard for loop with an index. The
enhanced for loop is also less error-prone
because Java automates the setup and processing
of the loop control information. - However, this type of loop cannot be used to
- move through an array in reverse, from last
position to the first position - add/change array elements
- track the index position of the current element
in an array - access any element other than the current element
on each pass
Java Concepts 7.4 (The Enhanced for Loop)
16Enhanced for Loop
- In general, its also not a good idea to use an
enhanced for loop on an array thats not filled. - So,
- be sure the array is filled
- be sure that youre going to visit each element
from the first to the last, - Be sure that you dont need to assign a value to
an element at a given position
Java Concepts 7.4 (The Enhanced for Loop)
17Enhanced for Loop
- To sum up all the elements in an array
Using a Standard for loop int sum 0 for (int
i 0 i lt allScores.length i) sum
allScoresi
Using an Enhanced for loop int sum 0 for (int
score allScores) // enhanced for loop
sum score
Java Concepts 7.1 (Arrays)
18Enhanced for Loop
- Beginning in 2007, students started seeing the
for each loop in AP Exams. - There arent any trick questions the for each
loop will simply be used in situations in which
students shouldnt waste time with indexes or
iterators.
Java Concepts 7.4 (The Enhanced for Loop)
19TestScores
- Create a TestScores class and TestScoresViewer
client class to do the following. The TestScores
class should contain the following two methods - Write a inputScores() method that continually
prompts the user for test scores. No more than
ten test scores should be entered. Test scores
are integer values between 0 and 110 (well
assume that up to 10 points extra credit could be
allowed on a test). Use an input dialog window
(use the JOptionPane.showInputDialog method). - If the user enters 999 then that indicates they
are finished entering values, and the program
should exit out of the loop. - Convert each test score entered into an integer
and store it into an array. - Keep track of how many test scores are entered.
- Write a processScores() method that loops through
this test scores array as follows - Read each value from the test scores array.
- Print each test score to the console on one line,
separated by commas (i.e. 100, 90, 85, 70). - Print the lowest test score to the console.
- Print the highest test score to the console.
- Print the average test score to the console.
- Note When printing values to the console, be
descriptive.
20TestScoresViewer
- The TestScoresViewer client class should look
like the following - public class TestScoresViewer
-
- public static void main(String args)
-
- TestScores scores new TestScores()
- scores.inputScores() //input all test
scores - scores.processScores() //print scores, min,
max, and average -
21Looping Through Arrays
- Count the Occurrences
- Array studentNames is an array of String values.
Each element contains a first name of a student
in the class. Assume that variable searchName is
a String that contains the name you want to
search for. Write an enhanced for loop that will
count the number of times the value of variable
searchName appears in the array studentName.
Java Concepts 7.4 (The Enhanced for Loop)
22Looping Through Arrays
- Count the Occurrences
- We can determine how many times String searchName
occurs in the array by comparing searchName to
each element and incrementing count every time
there is a match
String searchName Tom //Assign some value to
searchName int count 0 for (String name
studentNames ) if (name.equals(searchName))
count //Found another
element equal to //searchName
Java Concepts 7.4 (The Enhanced for Loop)
23Declaring Arrays
- Arrays are objects and must be instantiated
before being used. - Several array variables can be declared in a
single statement like this - Or like this
int abc new int500 // array of 500
integers
int abc, xyz abc new int500 xyz new
int10
int abc new int500, xyz new int10
Java Concepts 7.1 (Arrays)
24Declaring Arrays
- Array variables are null before they are
instantiated and assigned array objects. - Failure to assign an array object can result in a
null pointer exception.
int abc abc1 10 // runtime error null
pointer exception
Java Concepts 7.1 (Arrays)
25Declaring Arrays
- Because arrays are objects, two variables can
refer to the same array
int abc, xyz abc new int5 //Instantiate
an array of 5 integers xyz abc //xyz
and abc refer to the same array xyz3 100
// Changing xyz changes abc as well. System.out.pr
intln (abc3) // 100 is displayed
Java Concepts 7.1 (Arrays)
26Declaring Arrays
- If we want abc and xyz to refer to two separate
arrays that happen to contain the same values, we
would copy all of the elements from one array to
the other as follows.
int abc new int10 for (int i 0 i lt 10
i) abci i // or any value int
xyz new int10 for (int i 0 i lt 10 i)
xyzi abci
Java Concepts 7.1 (Arrays)
27Declaring Arrays
- Because arrays are objects, Javas garbage
collector sweeps them away when they are no
longer referenced.
int abc new int10 int xyz new
int5 xyz null // the array is no longer
referenced so // the garbage collector
will sweep it away.
Java Concepts 7.1 (Arrays)
28Declaring Arrays
- Arrays can be declared, instantiated, and
initialized in one step. - The list of numbers between the braces is called
an initializer list.
int abc 10,20,25,9,11 // abc now
references an array of five integers.
What would the following print to the
console? int calcValue abc1abc4 System.out
.println(calcValue)
// prints 31
Java Concepts 7.1 (Arrays)
29Declaring Arrays
Here are arrays of doubles, booleans, Strings,
and Students
- double ddd new double10
- boolean bbb new boolean10
- String ggg new String10
- Student sss new Student10
- String str
-
- ddd5 3.14
- bbb5 true
- ggg5 "The cat sat on the mat."
- sss5 new Student()
- sss5.setName ("Bill")
- str sss5.getName() ggg5.substring(7)
- // str now equals "Bill sat on the mat."
Java Concepts 7.1 (Arrays)
30Declaring Arrays
- There is another way to declare array variables.
int aaa // aaa is an array
variable int bbb, ccc, ddd // bbb and ddd
are arrays, // but ccc
is an integer
Java Concepts 7.1 (Arrays)
31Parallel Arrays
- Parallel Arrays Separate arrays of the same
length that correspond to one another. They
could have different component data types. - Suppose we want to keep a list of people's names
(Strings) and ages (integers). - This can be achieved by using two parallel arrays
in which corresponding elements are related. - Thus, Bill's age is 20 and Mary's age is 24.
String name "Bill", "Sue", "Shawn", "Mary",
"Ann" int age 20 , 21 , 19 ,
24 , 20
Java Concepts 7.1 (Arrays)
32Parallel Arrays
- Here is a visual way of looking at parallel
arrays
names
ages
Bill
0
0
20
Sue
1
1
21
Shawn
2
2
19
Mary
3
3
24
Ann
4
4
20
Java Concepts 7.1 (Arrays)
33Parallel Arrays
- The next slide shows a segment of code that finds
the age of a particular person. - In this example, the parallel arrays are both
full and the loops use the instance variable
length. - When the arrays are not full, the code will need
an extra variable to track their logical sizes.
Java Concepts 7.1 (Arrays)
34Parallel Arrays
String name "Bill", "Sue", "Shawn", "Mary",
"Ann" int age 20 , 21 , 19 ,
24 , 20 int correspondingAge -1 int
i String searchName JOptionPane.showInpu
tDialog("What name do you want to search
for?") for (i 0 i lt name.length i)
if (searchName.equals(namei))
correspondingAge agei break if
(correspondingAge -1) System.out.println(sea
rchName " was not found.") else
System.out.println(searchName " is "
correspondingAge " years old.")
Java Concepts 7.1 (Arrays)
35Two-Dimensional Arrays
- Starting in May 2010, Two-Dimensional Arrays will
be included on the AP Exam. - Prior to 2010, two-dimensional arrays were not
included on the AP Exam except in the case study
Java Concepts 7.6 (Two-Dimensional Arrays)
36Two-Dimensional Arrays
- A table of numbers, for instance, can be
implemented as a two-dimensional array. The
figure shows a two-dimensional array with four
rows and five columns. - Suppose we name this array table then to
indicate an element in table, we specify its row
and column position, remembering that indexes
start at 0
int x table23 // Sets x to 11, the value
// in row 2, column 3
row
column
Java Concepts 7.6 (Two-Dimensional Arrays)
37Two-Dimensional Arrays
- Declare and Instantiate
- Declaring and instantiating two-dimensional
arrays is accomplished by extending the processes
used for one-dimensional arrays
int table new int 45 // The
variable named table can reference a //
two-dimensional array of integers. //
Instantiate table as an array of size 4,
// each of whose elements will reference an
// array of 5 integers.
Java Concepts 7.6 (Two-Dimensional Arrays)
38Two-Dimensional Arrays
- Initializer lists can be used with
two-dimensional arrays. This requires an array of
arrays. - The number of inner lists determines the number
of rows, and the size of each inner list
determines the size of the corresponding row. - The rows do not have to be the same size, but
they are in this example
int table 0, 1, 2, 3, 4, // row 0
10,11,12,13,14, // row 1
20,21,22,23,24, // row 2
30,31,32,33,34 // row 3
Java Concepts 7.6 (Two-Dimensional Arrays)
39Two-Dimensional Arrays
- Remember, all the elements of a two-dimensional
array must be of the same type, whether they are
integers, doubles, Strings, or whatever. - To determine the number of rows in the
2-dimensional array, you can use the length
variable (just like a 1-dimensional array). - To determine the number of columns in the
2-dimensional array, you can use the length
variable for an array element. - If we refer to the table 2-dim array from the
previous slide, what would the following print to
the console? - System.out.print(Number of rows
table.length) - Number of rows 4
- System.out.print(Number of columns
table0.length) - Number of columns 5
Java Concepts 7.6 (Two-Dimensional Arrays)
40Two-Dimensional Arrays
- The following code uses a two-dimensional array.
Each row represents a class period and each
column represents the students in that class
//The following code will print every student in
each class String students "Bill",
"Brenda", "Bob", "Bonnie",
"Sally", "Sam", "Sandra", "Steve" for (int
row 0 row lt students.length row) //loops
thru rows System.out.println("")
System.out.print("These students are in period "
(row1) " " ) for (int col 0 col lt
students0.length col) //loops thru columns
System.out.print( studentsrowcol
", " )
Java Concepts 7.6 (2-Dimensional Arrays)
41StudentTestScores class
Test Scores
Student Name
1st 2nd 3rd 4th
87
Gary
80
78
90
0
0
Susan
95
92
85
100
1
1
Bruce
62
75
70
81
2
2
Julie
105
75
80
92
3
3
Chuck
85
79
81
89
4
4
Luis
90
79
93
88
5
5
0
1
2
3
Note You do not have to use these exact students
or test scores
42StudentTestScores
- Create a StudentTestScores class and
StudentTestScoresViewer client class - In the StudentTestScores class, create a method
named printTestScores() - This class should keep track of test scores for
multiple students. Test scores are integer
values between 0 and 110 (well assume that up to
10 points extra credit could be allowed on a
test). - Create a normal one-dimensional array to keep
track of student names. Use an initializer list
to populate this array with 6 student names (6
elements). - Create a two-dimensional array to keep track of
multiple test scores per student. - 4 tests have been taken by each student.
- Each row number of this array will correspond to
the index of the student from the student names
array you just created. - Each column represents one of the four test
scores for the student. - Use an initializer list to populate the test
scores for each student. - Write a loop to process the two arrays as
follows - Loop through each student in the student array
- For each student, loop through the corresponding
test scores for that student - Output the student name and a list of his/her
test scores to the console similar to the
following. Also, calculate the average test
score for the studentBill had test scores of
75, 80, 80, 85. Test average is 80.0 - Test with a couple scenarios
- EXTRA CREDIT (5 points)
- Print the lowest test score (and the name of the
person that had it) to the console. - Print the highest test score (and the name of the
person that had it) to the console. - Print the class average test score (for all
students in the class) to the console.
43Working with Arrays That Are Not Full
- One might create an array of 20 ints but receive
only 5 ints from interactive input (remember the
TestScores program). - This array has a physical size of 20 cells but a
logical size of 5 cells currently used by the
application. - From the application's perspective, the remaining
15 cells contain garbage.
Java Concepts 7.1 (Arrays)
44Working with Arrays That Are Not Full
- It is possible to track the array's logical size
with a separate integer variable. - The following code segment shows the initial
state of an array and its logical size - Note that abc.length (the physical size) is 50,
whereas size (the logical size) is 0
int abc new int50 int size 0
Java Concepts 7.1 (Arrays)
45Working with Arrays That Are Not Full
- Processing Elements in an
- Array That Is Not Full
- When the array is not full, one must replace the
array's length with its logical size in the loop.
- Here is the code for computing the sum of the
integers currently available in the array abc
Java Concepts 7.1 (Arrays)
46Working with Arrays That Are Not Full
int abc new int50 int size 0 ... code
that puts values into some initial portion of the
array and sets the value of size (i.e. like
capturing scores in TestScores program) Then you
can use the size in the remaining code in the
program int sum 0 for (int i 0 i lt size
i) // size contains //the number of items in
the array sum abci
Show TestScores program at this point
Java Concepts 7.1 (Arrays)
47Working with Arrays That Are Not Full
- Inserting Elements into an Array
- The simplest way to insert a data element into an
array is to place it after the last populated
item in the array. - One must first check to see if there is an
element available (make sure you are not going
over the arrays length) and then remember to
increment the array's logical size. - The following code shows how to insert an integer
at the end of array abc
Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)
48Working with Arrays That Are Not Full
if (size lt abc.length) abcsize anInt
size
- When size equals abc.length, the array is full.
- The if statement prevents a range error
(ArrayIndexOutOfBoundsException) from occurring. - Remember that Java arrays are of fixed size when
they are instantiated, so eventually they could
become full.
Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)
49Working with Arrays That Are Not Full
- Removing Elements from an Array
- Removing a data element from the end of an array
requires no change to the array itself. - Simply decrement the logical size variable, thus
preventing the application from accessing the
garbage elements beyond that point (since your
program would always be checking the size
variable when processing the array). - Note It is not necessary, but depending on the
situation you may want to set the elements value
to the value assigned at its initial state (i.e.
0 if it is an int array, or null if it is a
String array)
remove
Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)
50Arrays of Objects
- Here is the Student class that we are referring
to in the following slides
public class Student String studentName
int scores new int3 //Constructor
method for Student object public Student
(String _studentName, int _score1, int _score2,
int _score3) studentName _studentName
scores0 _score1 scores1 _score2
scores2 _score3 public double
getAverage() //Returns the average for the
student double sum 0 for (int
i0 iltscores.length i)
sum scoresi if
(scores.length gt 0) return sum /
scores.length else return
-1
Java Concepts Quality Tip 7.2 (pages 276-277)
51Arrays of Objects
- Here are other useful methods in the Student
class
// Sets the name of the student to the name
passed to it public void setName(String _name)
studentName _name // Gets the name of
student and passes it back to the calling
program public String getName() return
studentName
Java Concepts Quality Tip 7.2 (pages 276-277)
52Arrays of Objects
- Arrays can hold objects of any type, or more
accurately, references to objects. - For example, if we created a Student class
object, we could declare, instantiate and fill an
array of students as follows - When an array of objects is instantiated, each
cell is null by default until assigned a new
object.
// Declare and reserve 10 cells for student
objects Student studentArray new
Student10 // Fill array with
students studentArray0 new Student("Tom",
100, 85, 90) studentArray1 new
Student("Sally", 80, 72, 70) studentArray2
new Student("Jerry", 91, 88, 85) studentArray3
new Student("Marsha", 99, 81,
85) studentArray4 new Student("Phil", 93,
85, 72) studentArray5 new Student("Evan",
77, 88, 99) studentArray6 new
Student("Paula", 86, 65, 80) studentArray7
new Student("Courtney", 71, 75,
62) studentArray8 new Student("Johnny", 60,
65, 56) studentArray9 new Student("Cheryl",
104, 99, 90)
Java Concepts Quality Tip 7.2 (pages 276-277)
53Arrays of Objects
- The following code segment prints the average of
all students in the studentArray. Pay special
attention to the technique used to send a message
to objects in an array
// Print the average of all students in the
array. double sum 0 for (int i 0 i lt
studentArray.length i) sum
studentArrayi.getAverage() //Send message to
object
//in array System.out.println("The class average
is " sum / studentArray.length)
Show Student and StudentTester classes
Java Concepts Quality Tip 7.2 (pages 276-277)
54Arrays and Methods
- When any object is used as a parameter to a
method, what actually gets passed is a reference
to the object and not the object itself. - The actual and formal parameters refer to the
same object, and changes the method makes to the
object's state are still in effect after the
method terminates.
Java Concepts 7.1 (Arrays)
55Arrays and Methods
In the figure, the method changes the student's
name to Bill, and after the method finishes
executing, the name is still Bill.
Actual Parameter
Student object
. Student student new Student(William,90,91,8
3) doSomethingToStudent( student ) . void
doSomethingToStudent (Student studentParm) .
studentParm.setName(Bill) .
Formal Parameter
Java Concepts 7.1 (Arrays)
56Arrays and Methods
- Arrays are objects, so the same rules apply.
- When an array is passed as a parameter to a
method, the method manipulates the array itself
and not a copy of the array. - Changes made to the array in the method are still
in effect after the method has completed its
execution. - Passing an array to a method leads to trouble if
the method accidentally mishandles the array. - A method can also instantiate a new object or a
new array and return it using the return
statement.
Java Concepts 7.1 (Arrays)
57Arrays and Methods
- Search for a Value
- The code to search an array for a value is used
so frequently in programs that it is worth
placing in a method. - Here is a method to search an array of integers.
- The method returns the location of the first
array element equal to the search value or -1 if
the value is not there
static int search (int a, int searchValue)
int location, i location -1 for (i 0
i lt a.length i) if (ai
searchValue) location i
break return location
Java Concepts 7.5 (Simple Array Algorithms)
58Arrays and Methods
- Copying an Array
- Write a method that will copy one array into
another array.
static int copyArray(int original) int
copy new intoriginal.length for (int i
0 i lt original.length i) copyi
originali return copy
- Here is the call to the method
int orig 1,2,3,4,5 int cp new
int5 cp copyArray(orig)
Java Concepts 7.7 (Copying Arrays)
59EmployeeNames
- Create an EmployeeNames class and
EmployeeNamesTester client class to do the
following - You are a programmer for a company of 10
employees. The owner of the company only hires
people whose first name begins with the last
character of their last name and their middle
name begins with the next-to-last character in
their last name (i.e. H. T. Smith or Z. E.
Lopez). You have been given only the last names
of each employee and have been asked to generate
a list of employee names using the first and
middle initials (i.e. you were given Jones, you
need to print S. E. Jones). - Since your boss is very controlling and wants to
make sure that you know how to pass arrays to
methods, he has given you the following strict
instructions on how to create the program - Your EmployeeNames class needs to have a static
method named convertName(). This method will be
the only method in this class and should do the
following - The method should accept an array of last names
as the input parameter. - The method should return an array of formatted
names (first and middle initials and last name) - Loop through the array of last names that is sent
to the method. - For each element, it should determine the first
initial and middle initial of the name and format
it correctly (H. T. Smith) - It should store each of these formatted names as
elements in a formatted names array. - After processing all the names, the method should
return the formatted names array back to the
calling program. - Create a driver program named EmployeeNamesTester.
Create a main() method in this class and do the
following in the main() method - Create an array of employee last names (there are
up to 10 employees). You need to populate this
array with last names by either using an
initializer list or prompting the user (see extra
credit). - Declare and instantiate an array of formatted
names that will be used to store the name with
first and middle initials. - Call the EmployeeNames.convertName method and
pass it the array of last names. - Assign the returned array to the formatted names
array you created in the main method. - Loop through the formatted names and print them
to the console on separate lines. - EXTRA CREDIT (5 points)
- Input the last names instead of using an
initializer list and handle the situation where
the last names array is not full.