You are on page 1of 49

Arrays

Objectives
After studying this chapter, you should be
able to:
Elaborate the use of arrays.
Declare and use an array of primitive data types
in writing a program.
Apply array of objects in developing a program
Apply the principles of arrays in linear search
(sequential search) and bubble sort.

Array Basics
An array is a collection of data values.
If your program needs to deal with 100 integers, 500
Account objects, 365 real numbers, etc., you will use
an array.
In Java, an array is an indexed collection of data values
of the same type.
Types of Arrays:
- one-dimensional array
- two-dimensional array
- multidimensional array
3

Arrays of Primitive Data Types


Array Declaration
<data type> [ ] <variable> //variation 1
<data type> <variable> [ ] //variation 2

Array Creation
<variable>

Example

= new <data type> [ <size> ]


Variation 1

Variation 2

double[ ] rainfall;

double rainfall [ ];

rainfall

rainfall

= new double[12];

= new double[12];

An array is like an object!


4

Accessing Individual Elements


Individual elements in an array accessed with the indexed expression.

double[] rainfall = new double[12];

rainfall

The index of the first


position in an array is 0.

rainfall[2]

10

11

This
Thisindexed
indexedexpression
expression
refers
to
the
element
refers to the elementatat
position
position#2
#2

Array Processing Sample1


double[] rainfall = new double[12];
double

annualAverage, sum = 0.0;

The
Thepublic
publicconstant
constant
length
returns
length returnsthe
the
capacity
of
an
capacity of an
array.
array.

for (int i = 0; i < rainfall.length; i++) {


System.out.println(Rainfall for month + (i +1) +
=);
rainfall[i]

=Double.parseDouble(input.readLine());

sum += rainfall[i];
}
annualAverage = sum / rainfall.length;

Array Processing Output


Rainfall for month 1=100.00
Rainfall for month 2=120.00
Rainfall for month 3=200.00
Rainfall for month 4=200.00
Rainfall for month 5=300.00
Rainfall for month 6=150.00
Rainfall for month 7=100.00
Rainfall for month 8=145.00
Rainfall for month 9=125.00
Rainfall for month 10=200.00
Rainfall for month 11=200.00
Rainfall for month 12=300.00
Average is = 178.33
Press any key to continue...

Array Processing Sample 2


double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] = "January";
monthName[1] = "February";
double

The
Thesame
samepattern
pattern
for
the
remaining
for the remaining
ten
tenmonths.
months.

annualAverage, sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {


System.out.print("Rainfall for "+monthName[i]+ "=");
rainFall[i] = Double.parseDouble(input.readLine());
sum += rainFall[i];
}
annualAverage = sum / rainfall.length;
8

Array Processing Output


Rainfall for January=150.00
Rainfall for February=250.00
Average is = 200.00
Press any key to continue...

Array Initialization
Like other data types, it is possible to declare
and initialize an array at the same time.
int[] number = { 2, 4, 6, 8 };
double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,
9.00, 3.123, 22.084, 18.08 };
String[] monthName = { "January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

number.length
samplingData.length
monthName.length

4
9
12
10

Variable-size Declaration
In Java, we are not limited to fixed-size array
declaration.
The following code prompts the user for the size of an
array and declares an array of designated size:
int size;
int[] number;
System.out.print(Size of Array :);
size= Integer.parseInt(input.readLine());
number = new int[size];
11

Arrays of Objects
In Java, in addition to arrays of primitive
data types, we can declare arrays of objects
Can use arrays to manipulate objects.
The use of an array of objects allows us to
model the application more cleanly and
logically.

12

Code

Creating an Object Array - 1


A
A

Person[ ]

person;

person = new Person[20];


person[0] = new

Only
Onlythe
thename
nameperson
person
isisdeclared,
no
array
declared, no arrayisis
allocated
allocatedyet.
yet.

Person( );

person

State
of
Memor
y

A is executed
After A
13

Code

Creating an Object Array - 2


Person[ ]

B
B

person;

person = new Person[20];


person[0] = new Person( );

Now
Nowthe
thearray
arrayfor
forstoring
storing
20
Person
objects
is
20 Person objects is
created,
created,but
butthe
thePerson
Person
objects
themselves
objects themselvesare
are
not
yet
created.
not yet created.

person

State
of
Memor
y

After B
B is executed

16 17 18 19

14

Code

Creating an Object Array - 3


Person[ ]

person;

person = new Person[20];


person[0] = new Person( );

C
C

One
OnePerson
Personobject
objectisis
created
createdand
andthe
thereference
reference
totothis
object
is
placed
this object is placedinin
position
position0.0.

person

State
of
Memor
y

16 17 18 19

Person

After C
C is executed
15

Example : Class PersonOperation_1


import java.io.*;
class PersonOperation_1
{
private Person [] person;
public PersonOperation_1(){
person = new Person[1];
person[0] = new Person();
}
public void addRecord(){
person[0].setName("Latte");
person[0].setAge(21);
person[0].setGender('L');
}
16

Example : Class PersonOperation_1(Cont)


public void displayRecord(){
System.out.println("\n\nNama =
"+person[0].getName());
System.out.println("Age = "+person[0].getAge());
System.out.println("Gender =
"+person[0].getGender());
}
public static void main(String[] arg)
{
PersonOperation_1 people = new PersonOperation_1();
people.addRecord();
people.displayRecord();
}
} // end class PersonOperation_1
17

Example : Class Person


import java.io.*;
class Person
{
private String name;
private int age;
private char gender;
public Person(String newName, int newAge, char newGender){
name = newName;
age = newAge;
gender = newGender;
}
public void setName(String newName)
{
name = newName;
}

18

Example : Class Person (Cont)


public void setAge(int newAge){
age = newAge;
}
public void setGender(char newGender){
gender = newGender;
}
public String getName(){
return name;
}
public int getAge()
{
return age;
}
public char getGender()
{
return gender;
}

19

Class PersonOperation_2 in detail dynamic data


import java.io.*;
import java.lang.*;
class PersonOperation_2
{
private Person [] person;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(read);
public PersonOperation_2()
{
person = new Person[2];
}
public void addRecord() throws IOException
{
String name = null, sex=null;
int age;
char gender;
System.out.println("\n");
for (int i= 0; i< person.length; i++)
{
System.out.print("\nEnter name = ");
name = input.readLine();
System.out.print("Enter age = ");
age = Integer.parseInt(input.readLine());
System.out.print("Enter gender = ");
sex = input.readLine();
gender = sex.charAt(0);
person[i] = new Person(name,age,gender);
}
}

20

Class PersonOperation_2 in detail dynamic data (Cont.)

public void displayRecord()


{
for (int i= 0; i< person.length; i++)
{
System.out.println("\n\nNama =
"+person[i].getName());
System.out.println("Age = "+person[i].getAge());
System.out.println("Gender =
"+person[i].getGender());
}
}
public static void main(String[] arg) throws IOException
{
PersonOperation_2 people = new PersonOperation_2();
people.addRecord();
people.displayRecord();
}
} // end ersonOperation_2
21

Person Array Processing


the youngest
and oldest persons.
Find
Sample
1
int

minIdx = 0;

//index to the youngest person

int

maxIdx = 0;

//index to the oldest person

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


if ( person[i].getAge() < person[minIdx].getAge() ) {
minIdx

= i;

//found a younger person

} else if (person[i].getAge() > person[maxIdx].getAge() ) {


maxIdx

= i;

//found an older person

}
}
//person[minIdx] is the youngest and person[maxIdx] is the oldest
22

Person Array Processing


Sample
2 Approach 1
Object Deletion
Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totonull.
null.

int delIdx = 1;

A
A

person[delIdx] = null;

person

person
0

AA

BB

CC

D
D

Before A
A is executed

AA

CC

D
D

After A
A is executed

23

Person Array Processing


Sample
2. (cont)
Object Deletion
Approach 2
int delIdx = 1, last = 3;

A
A

person[delIndex] = person[last];
person[last]

person

= null;

person
0

AA

Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totothe
thelast
last
person.
person.

BB

CC

D
D

Before A
A is executed

AA

D
D

CC

After A
A is executed

24

Person Array Processing


for a particular
Searching
Sample
3 person. Approach 2 Deletion is used.
int i = 0;
while ( person[i] != null && !person[i].getName().equals("Latte") ) {
i++;
}
if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}

25

Code

Passing Arrays to Methods


Step 1

A
A

minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{
}

At

A
A before searchMinimum

arrayOne

State of
Memory

A.
A.Local
Localvariable
variable

number
numberdoes
does not
not
exist
before
the
exist before the
method
methodexecution
execution

26

Passing Arrays to Methods 2


Passing Arrays to Methods .
Step 2
minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[] number))


{

B
B

B
The address is copied at B
arrayOne

State of
Memory

number

B.
B.The
Thevalue
valueofofthe
the
argument,
argument,which
whichisis
an
anaddress,
address,isis
copied
copiedtotothe
the
parameter.
parameter.

27

Passing Arrays to Methods .


Step 3
minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{

C
C

While at C
C inside the method
arrayOne

State of
Memory

number

C.
C.The
Thearray
arrayisis
accessed
accessedvia
via
number
inside
number inside
the
themethod.
method.

28

Passing Arrays to Methods


Step 4
D
D

minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{
}

D after searchMinimum
At D

arrayOne
arrayOne

State of
Memory

number

D.
D.The
Theparameter
parameterisis

erased.
erased.The
Theargument
argument
still
points
to
the
still points to thesame
same
object.
object.

29

Two-Dimensional Arrays
Two-dimensional arrays are useful in representing tabular information.

30

Two-Dimensional Arrays
Declaration a two-dimensional arrays
<data type> [][] <variable>
<data type>
<variable>[][]

//variation 1
//variation 2

Creation a two-dimensional arrays


<variable>

= new <data type> [intRow][intColumn ]

Example
double[][] payScaleTable;
payScaleTable
= new double[4][5];

payScaleTable

0
1
2
3

31

Two-Dimensional Arrays
An element in a two-dimensional array is
accessed by its row and column index.

32

Two-Dimensional Arrays
Find the average of each row.
double[ ] average = { 0.0, 0.0, 0.0, 0.0 };
for (int i = 0; i < payScaleTable.length; i++) {
for (int j = 0; j < payScaleTable[i].length; j++) {
average[i] += payScaleTable[i][j];
}
average[i] = average[i] / payScaleTable[i].length;
}

33

Basic operations performed on arrays:


Searching
Array Applications
Sorting
Searching - the process of looking for a specific
element in an array; for example, discovering whether
a certain score is included in a list of scores.
Sorting - the process of arrange elements of arrays in
ascending or descending order.
34

There are many algorithms and data structures devoted to


searching and sorting elements of arrays.

Array Applications

Searching
Linear Search
Binary Search
Sorting
Bubble sort
Insertion Sort
Selection Sort

In this section, linear search and bubble sort are discussed.


35

Linear Search
The linear search is also known as sequential
search, compares the key element, key,
sequentially with each element in the array list.
The method continues to do so until the key
matches an element in the list or the list is
exhausted without a match being found.
If a match is made, the linear search returns the
index of the element in the array that matches the
key. If no match is found, the search returns -1.
36

Linear Search
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}

Trace the method


int[]
int i
int j
int k

list = {1, 4, 4, 2, 5, -3, 6, 2};


= linearSearch(list, 4); // returns 1
= linearSearch(list, -4); // returns -1
= linearSearch(list, -3); // returns 5
37

Linear Search
public class Search{
public void printout(int marks[ ])
{
System.out.print("Elements of Array :");
for (int k=0; k <marks.length; k++)
System.out.print( marks[k] + "\t");
System.out.println();
} // end printout method
public int searchLinear(int marks[ ], int key)
{
for (int k=0; k <marks.length; k++)
if (marks[k] == key)
return k; // return indeks if found
return 1; // return 1 if not found
} // end searchLinear method

38

Linear Search
public static void main(String [] arg)
{
int studMark [ ] = {21,20,27,24,19};
Search searching = new Search();
searching.printout(studMark);
int a= searching.searchLinear(studMark,24);
System.out.println("Index = " + a);
int b = searching.searchLinear(studMark,5);
System.out.println("Index = " + b);
} // end main
} // end class
39

Linear Search
Output:
Elements of Array :21 20 27 24 19
Index = 3
Index = 1
Process Exit...

40

Bubble Sort
Sort the elements of array in increasing
order.
Example : 10 7 19 5 16
sort in increasing order
5 7 10 16 19

41

Bubble Sort
The bubble sort algorithm works as follows:
Suppose list[0].list[n-1] is a list of n elements, indexed 0 to
n-1.
list [0] [1] [2] [3] [4]

21 20 27 24 19
In a series of n 1 iterations, the successive elements,
list[index] and list[index +1] of list are compared. If list[index]
is greater than list [index + 1], then the elements list[index] and
list[index +1] are swapped, that is, interchanged.
It follows that the smaller elements move toward the top, and
the larger elements move towards the bottom.
42

Bubble Sort
Iteration 1

Iteration 2

[0] [1] [2] [3] [4]

[0] [1] [2] [3] [4]

21 20 27 24 19

20 21 24 19 27

20 21 27 24 19

20 21 24 19 27

20 21 27 24 19

20 21 24 19 27

20 21 24 27 19

20 21 19 24 27

20 21 24 19 27

20 21 19 24 27
43

Bubble Sort
Iteration 3

Iteration 4

20 21 19 24 27

20 19 21 24 27

20 21 19 24 27

19 20 21 24 27

20 19 21 24 27

19 20 21 24 27

20 19 21 24 27

19 20 21 24 27
19 20 21 24 27

20 19 21 24 27

sorted list : 19 20 21 24 27
44

Bubble Sort
public class TestBubbleSort {
void bubbleSort(int list[], int listLength)
{
int temp;
int counter, index;
for(counter=0; counter <listLength -1; counter++)
{
for(index=0; index<listLength-1-counter;index++)
if (list[index] > list[index +1]){
temp = list[index];
list[index] = list[index +1];
list[index + 1] = temp;
}
}
}

45

Bubble Sort
public static void main(String[] args)
{
int list[]={10, 7, 19, 5};
int i;
TestBubbleSort sort = new TestBubbleSort();
sort.bubbleSort(list, 4);
System.out.print("After sorting, the list
elements are:");
for(i=0; i<4; i++)
System.out.print(list[i] + "");
System.out.println();
}
}

46

Bubble Sort
Output:
After sorting, the list elements are:
5 7 10 19

47

References
Thomas Wu. C, An Introduction To Object-

Oriented Programming With Java. (2006). Mc


Graw Hill.
Liang, D. (2006). Introduction To Java
programming. Prentice Hall.

48

Exercise
Look at your handout.
Read and understand
the given instruction.
Answer now.

49

You might also like