You are on page 1of 29

2012 Pearson Education, Inc. All rights reserved.

Chapter 8:
Arrays
Starting Out with Java:
From Control Structures through Data Structures
Second Edition
by Tony Gaddis and Godfrey Muganda

Activity - Rules of the Vocabulary Game


1.) The Team that has the greatest participation will win 10 points
extra credit for each team member.
2.) Each person in table must write a definition or example of a
concept.
3.) Main* topics to take notes about or provide an example:
a.) How to define an array
b.) Two ways to initialize an array
c.) How to access any element in an array
d.) A loop used to traverse an array
e.) What is a parallel array?
f.) How to check the bounds of an array, prevent off-by-one
errors?
*Feel free to take notes/give examples about any other topics related to arrays.
2012 Pearson Education, Inc. All rights reserved.

Introduction to Arrays
Primitive variables are designed to hold only
one value at a time.
Arrays allow us to create a collection of like
values that are indexed.
An array can store any type of data but only
one type of data at a time.
An array is a list of data elements.
2012 Pearson Education, Inc. All rights reserved.

8-3

Creating Arrays
An array is an object so it needs an object reference.
// Step 1: Declare a reference to an array that will hold
integers.

int[] numbers;
// Step 2: Create a new array that will hold 6 integers.

numbers = new int[6];

index 0

index 1

index 2

index 3

index 4

index 5

Array element values are initialized to 0.


Array indexes always start at 0.
2012 Pearson Education, Inc. All rights reserved.

8-4

Creating Arrays~ continued


It is possible to declare an array reference and create it in
the same statement.
// Declare and instantiate in 1 Step:

int[] numbers = new int[6];


Note: Once created, an array size is fixed and cannot be changed.

Arrays may be of any type.


float[] temperatures = new float[100];
char[] letters = new char[41];
long[] units = new long[50];
double[] sizes = new double[1200];
String [] names = new String[10];
2012 Pearson Education, Inc. All rights reserved.

8-5

Accessing the Elements of an Array


20

numbers[0]

numbers[1]

numbers[2]

numbers[3]

numbers[4]

numbers[5]

An array is accessed by:


the reference name
An index that identifies which element in the array to access.
numbers[0] = 20; //pronounced "numbers at index zero"

2012 Pearson Education, Inc. All rights reserved.

8-6

Traversing an Array to populate it


Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];

for (int i = 0; i < 10; i++)


{
System.out.println(Enter a number);
numbers[i] = keyboard.nextInt();
}

2012 Pearson Education, Inc. All rights reserved.

Traversing an Array to access it


for (int i = 0; i < 10; i++)
{

System.out.println(Number: + numbers[i]);

}
The Enhanced for Loop
an alternative to accessing the array
for(int val : numbers)
{
System.out.println(Number: " + val);
}
Enhanced for-Loops = simplified array processing (read only)
Always goes through all elements

2012 Pearson Education, Inc. All rights reserved.

for(datatype elementVariable : array)


{ statement;}

Array Initialization an alternative


When relatively few items need to be initialized, an
initialization list can be used to initialize the array.
int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

The numbers in the list are stored in the array in order:

days[0] is assigned 31,


days[1] is assigned 28,
days[2] is assigned 31,
days[3] is assigned 30,
etc.

2012 Pearson Education, Inc. All rights reserved.

8-9

Bounds Checking
Array indexes always start at zero and continue to
(array length - 1).
int[] values = new int[10];

This array would have indexes 0 through 9.


In for loops, it is typical to use i, j, and k as counting
variables.
It might help to think of i as representing the word index.

2012 Pearson Education, Inc. All rights reserved.

8-10

Off-by-One Errors
It is very easy to be off-by-one when accessing arrays.
// This code has an off-by-one error.
int[] numbers = new int[10];
for (int i = 1; i <= 10;
10 i++)
{numbers[i] = 0;}

Index
out of
bounds

Here, the equal sign allows the loop to continue on to index 10,
where 9 is the last index in the array.
This code would throw an
ArrayIndexOutOfBoundsException.
2012 Pearson Education, Inc. All rights reserved.

8-11

The length field & the length method


Arrays have a final field named length.
Use the .length field to check for boundaries of a table

for (int i = 1; i < numbers.length; i++)


{numbers[i] = 0;}

String objects have a method named length().


for (int i = 0; i < names.length; i++)
System.out.println(names[i].length());
2012 Pearson Education, Inc. All rights reserved.

Activity
1.) Lets define an array of your top 10 favorite music artists.
2.) Create a for-loop to ask the user for each name of their fav
artist.
a.) Use the for-loop index as the index of the array.
3.) Create a separate (parallel) array of your favorite song for
each artist, in exactly the same order as the artist array.
a.) Use the for-loop again to initialize it.
4.) Print the 2 parallel arrays, formatting the output so that the
artist name is printed first, and beside it favorite song for that
artist.
2012 Pearson Education, Inc. All rights reserved.

Activity Another Round of the Vocabulary Game


1.) The Team that has the greatest participation will win 10 points extra credit for
each team member. Each person in table must write a definition or example of a
concept.

2.) Main* topics to take notes about & provide an example:


a.) How to copy an array
b.) How to receive an array as a parameter, & return an array from a
method.
c.) How to compare elements in 2 arrays
d.) How to find:
1.) highest & lowest element in an array
2.) sum & average of all elements in an array

2012 Pearson Education, Inc. All rights reserved.

2 re f
er e
varia nce
b
point les, are
in g to
on e a
r
mem ray in
ory.

Copying Arrays

This is not the way to copy an array.

int[] array1 = { 2, 4, 6, 8, 10 };
int[] array2 = array1; //This does not copy
2
array1 holds an
address to the array

Address

array2 holds an
address to the array

Address

arrays.

8 10

Instead,
Instead you need to copy each element of one array to another:
ay
W
t
gh
Ri !!!

int[] firstArray = {5, 10, 15, 20, 25 };


int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
{ secondArray[i] = firstArray[i]; }

2012 Pearson Education, Inc. All rights reserved.

8-15

Passing Arrays as Arguments


Arrays are objects.
objects
Their references can be passed to methods like any
other object reference variable.
showArray(numbers);
numbers

5 10 15 20 25 30 35 40

Address

public static void showArray(int[] array)


{
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
2012 Pearson Education, Inc. All rights reserved.

8-16

Returning an Array Reference


A method can return a reference to an array.
The return type of the method must be declared as an array of
the right type.
public static double[] getArray()
{
double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 };
return array;
}

The getArray method is a public static method that returns an


array of doubles.
Note: If you are receiving an array as a parameter, you do not have
to explicitly return it as a return type, since any changes done to the
array in the method will be permanent, even outside the method.
2012 Pearson Education, Inc. All rights reserved.

8-17

Comparing Arrays: An Example

int[] firstArray = { 2, 4, 6, 8, 10 };
int[] secondArray = { 2, 4, 6, 8, 10 };
boolean arraysEqual = true;
int i = 0;

// First determine whether the arrays are the same size.


if (firstArray.length != secondArray.length)
arraysEqual = false;
// Next determine whether the elements contain the same data.
while (arraysEqual && i < firstArray.length)
Wh
{
y
to u is it b
if (firstArray[i] != secondArray[i])
loo se a w etter
ph
h
er e? i l e
arraysEqual = false;
i++;
}
if (arraysEqual)
System.out.println("The arrays are equal.");
else
System.out.println("The arrays are not equal.");
2012 Pearson Education, Inc. All rights reserved.

8-18

Useful Array Operations


Finding the Highest Value
int [] numbers = {7, 3, 1, 9, 5};
int highest = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] > highest)
highest = numbers[i];
}
Finding the Lowest Value
int lowest = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] < lowest)
lowest = numbers[i];
}
2012 Pearson Education, Inc. All rights reserved.

8-19

More Useful Array Operations


Summing Array Elements:
int total = 0; // Initialize accumulator
for (int i = 0; i < units.length; i++)
{ total += units[i]; }

Averaging Array Elements:


double total = 0; // Initialize accumulator
double average; // Will hold the average
for (int i = 0; i < scores.length; i++)
{ total += scores[i]; }
average = total / scores.length;

2012 Pearson Education, Inc. All rights reserved.

8-20

Activity
1.) In main, define an array of your own grades, where each element
of the array is the score you received on each of your labs and
homework assignments (define & initialize in 1 step).
2.) In the same driver class, create a static method called
calculateGradesStatistics(double[] myArray). This method will
receive your array of grades as an input parameter.
3.) In the method, use a for-loop that will determine:
a.)
b.)
c.)
d.)
e.)

The highest score


The lowest score
The sum of all the scores
The average of all the scores
Print each of the above statistics after the for-loop is over.

2012 Pearson Education, Inc. All rights reserved.

Activity Final Round of the Vocabulary Game


1.) The Team that has the greatest participation will win 10 points extra credit for
each team member. Each person in table must write a definition or example of a
concept.

2.) Main* topics to take notes about or provide an example:


a.) How to save an array to a file, & load an array from a file
b.) How to create & use an array of String objects
c.) How to create an array of any object

2012 Pearson Education, Inc. All rights reserved.

Arrays and Files ~ Saving an array to a file


Saving the contents of an array to a file:
int[] numbers = {10, 20, 30, 40, 50};
PrintWriter outputFile =
new PrintWriter ("Values.txt");
for (int i = 0; i < numbers.length; i++)
outputFile.println(numbers[i]);
outputFile.close();

2012 Pearson Education, Inc. All rights reserved.

8-23

Arrays & Files ~ Loading an array from a file


Reading the contents of a file into an array:
final int SIZE = 5; // Assuming we know the size.
int[] numbers = new int[SIZE];
int i = 0;
File file = new File ("Values.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext() && i < numbers.length)
{
numbers[i] = inputFile.nextInt();
i++;
}
inputFile.close();

2012 Pearson Education, Inc. All rights reserved.

8-24

String Arrays ~ Define & Initialize in 1 Step:


An array of String objects can be created:
String[] names = { "Bill", "Susan", "Steven", "Jean" };
The names variable holds
the address to the array.

A String array is an array


of references to String objects.

Address
names[0]

address

Bill

names[1]

address

Susan

names[2]

address

Steven

names[3]

address

Jean

2012 Pearson Education, Inc. All rights reserved.

8-25

String Arrays ~ Using 2 Steps:


If an initialization list is not provided, the new keyword must
be used to create the array:
String[] names = new String[4];
The names variable holds
the address to the array.
Address
names[0]

null

names[1]

null

names[2]

null

names[3]

null

2012 Pearson Education, Inc. All rights reserved.

When an array is created in this


manner, each element of the array
must be initialized.
names[0]
names[1]
names[2]
names[3]

=
=
=
=

"Bill";
"Susan";
"Steven";
"Jean";

Using String Methods On each element of a


String Array
String objects have several methods, including:

toUpperCase
compareTo
equals
charAt

Each element of a String array is a String object.


object
String Methods can be used by referencing the array name
and index:
System.out.println(names[0].toUpperCase());
char letter = names[3].charAt(0);
2012 Pearson Education, Inc. All rights reserved.

8-27

Arrays of Objects An Alternative to Parallel Arrays


This is an array of references to BankAccount objects:
BankAccount[] accounts = new BankAccount[5];
The accounts variable holds the addres
of an BankAccount array.
Address
accounts[0]

null

accounts[1]

null

accounts[2]

null

accounts[3]

null

accounts[4]

null

Each element needs to be initialized.


for (int i = 0; i < accounts.length; i++)
{ accounts[i] = new BankAccount();}

2012 Pearson Education, Inc. All rights reserved.

balance:

0.0

balance:

0.0

balance:

0.0

balance:

0.0

balance:

8-28
0.0

Final Array Activity In 2 Groups


Group 1 in Table:
1.) Lets create a text file, students.txt, that will contain the following fields, separated by a
space:
a.) Last Name
b.) First Name c.) Student ID
d.) GPA
Create a new Netbeans Project, and copy the students.txt file in the same directory as the project.

2.) Define a Student class, with the 4 attributes defined above. Create a .toString() method in
the Student class, that will return the first name + last name + student id + GPA.
Group 2 in Table:
3.) Define a Driver class. In the main method, read each record from students.txt, and create a
Student object from each record. Call a static method that will receive the name of the
students.txt file, and will create and return an array of Student objects.
4.) Print the array of Student objects.
5.) Copy the selectionSort() method from Lab #7 to the bottom of the Driver class. Adjust the
logic to sort by GPA.
6.) Invoke the selection sort method, passing it the array of Student objects. Print the array
of Student objects again (should be sorted).
2012 Pearson Education, Inc. All rights reserved.