0% found this document useful (0 votes)
4 views24 pages

Chapter6 Arrays

Chapter 6 covers arrays in Java, including their declaration, creation, and manipulation of both primitive data types and objects. It explains how to access individual elements, process arrays, and pass them to methods. The chapter also discusses two-dimensional arrays and provides examples for practical understanding.

Uploaded by

salmaalsaeed3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

Chapter6 Arrays

Chapter 6 covers arrays in Java, including their declaration, creation, and manipulation of both primitive data types and objects. It explains how to access individual elements, process arrays, and pass them to methods. The chapter also discusses two-dimensional arrays and provides examples for practical understanding.

Uploaded by

salmaalsaeed3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapter 6: Arrays

Objectives
• After studying this chapter, Stdent should
be able to
• Manipulate a collection of data values, using an
array.
• Declare and use an array of primitive data types in
writing a program.
• Declare and use an array of objects in writing a
program
• Define a method that accepts an array as its
parameter and a method that returns an array
• Describe how a two-dimensional array is
implemented as an array of arrays
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.

Page 3 11/2/2008
Arrays of Primitive Data Types
• Array Declaration

<data type> [ ] <variable>


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

• Array Creation

<variable>
Variation= 1new <data type> [ <size> ]
Variation 2
• Example
double[ ] rainfall; double rainfall [ ];
rainfall rainfall
= new double[12]; = new double[12];

An array is like an object!


Page 4 11/2/2008
Accessing Individual Elements
• Individual elements in an array accessed with
the indexed expression.
double[] rainfall = new double[12];

rainfall
0 1 2 3 4 5 6 7 8 9 10 11

This
Thisindexed
indexedexpression
expression
refers
refers to the elementatat
to the element
The index of the first rainfall[2] position
position#2
#2
position in an array is 0.

Page 5 11/2/2008
Array Processing – Sample1
double[] rainfall = new double[12];
The
Thepublic
publicconstant
constant
length
length returnsthe
returns the
double annualAverage, capacity of an array.
capacity of an array.
sum = 0.0;

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

rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for month " + (i+1) ) );
sum += rainfall[i];
}

annualAverage = sum / rainfall.length;

Page 6 11/2/2008
Array Processing – Sample 2
double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] = "January";
The
Thesame
samepattern
pattern
monthName[1] = "February"; for the remaining
for the remaining
… ten
tenmonths.
months.
double annualAverage, sum = 0.0;

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


rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for "
+ monthName[i] ));
sum += rainfall[i];
} The
Theactual
actualmonth
month
annualAverage = sum / rainfall.length; name
name insteadofofaa
instead
number.
number.

Page 7 11/2/2008
Array Processing – Sample 3
• Compute the average rainfall for each
quarter.
//assume rainfall is declared and initialized properly

double[] quarterAverage = new double[4];

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


sum = 0;
for (int j = 0; j < 3; j++) {
//compute the sum of
sum += rainfall[3*i + j]; //one quarter
}
quarterAverage[i] = sum / 3.0; //Quarter (i+1) average
}

Page 8 11/2/2008
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 4
samplingData.length 9
monthName.length 12

Page 9 11/2/2008
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
int size;
size:
int[] number;

size= Integer.parseInt(JOptionPane.showInputDialog(null,
"Size of an array:"));

number = new int[size];

Page 10 11/2/2008
Arrays of Objects
• In Java, in addition to arrays of
primitive data types, we can declare
arrays of objects
• An array of primitive data is a powerful
tool, but an array of objects is even
more powerful.
• The use of an array of objects allows us
to model the application more cleanly
and logically.
Page 11 11/2/2008
public class Person
{
private String name;
private int age;
private char gender;

public Person()
{age=0; name=" "; gender=' ';}

public Person(String na, int ag, char gen)


{setAge(ag); setName(na); setGender(gen); }

public Person(Person pr)


{ setPerson(pr);}

public void setPerson(Person p)


{ age=p.age; gender =p.gender;
name=p.name. substring(0, p.name.length());
}

public void setAge (int a) {age=a;}


public void setGender (char g) {gender=g;}
public void setName(String na)
{name=na.substring(0, na.length());}

public int getAge(){return age;}

public char getGender () {return gender;}

public String getName () { return name;}

}
Page 12 11/2/2008
The Person Class
• We will use Person objects to illustrate the use of
an array of objects.

public class Person


{
private String name;
private int age;
private char gender;
public Person() {age=0; name=" "; gender=' ';}
public Person(String na, int ag, char gen) {setAge(ag); setName(na); setGender(gen); }
public Person(Person pr) { setPerson(pr);}
public void setPerson(Person p)
{ age=p.age; gender =p.gender;
name=p.name. substring(0, p.name.length()); }
public void setAge (int a) {age=a;}
public void setGender (char g) {gender=g;}
public void setName(String na)
{name=na.substring(0, na.length());}
public int getAge(){return age;}
public char getGender () {return gender;}
public String getName () { return name;}
}

Page 13 11/2/2008
Creating an Object Array - 1
Code A
A Person[ ] person;
person = new Person[20]; Only
Onlythe
thename
nameperson
personisis
declared,
declared,no
noarray
arrayisis
person[0] = new Person( ); allocated
allocatedyet.
yet.

person

State
of
Memory
After A
A is executed

Page 14 11/2/2008
Creating an Object Array - 2
Code Person[ ] person; Now
Nowthe
thearray
arrayfor
forstoring
storing
20 Person objects
20 Person objects isis
B
B person = new Person[20]; created,
created,but
butthe
thePerson
Person
objects
objects themselvesare
themselves are
person[0] = new Person( );
not yet created.
not yet created.

person

0 1 2 3 4 16 17 18 19

State
of
Memory
After B
B is executed

Page 15 11/2/2008
Creating an Object Array - 3
Code Person[ ] person; One
OnePerson
Personobject
objectisis
person = new Person[20]; created
createdand
andthe
thereference
reference
totothis
this object is placedinin
object is placed
C
C person[0] = new Person( ); position
position0.0.

person

0 1 2 3 4 16 17 18 19

State
of Person

Memory
After C
C is executed

Page 16 11/2/2008
Person Array Processing –
Sample 2
• Find the youngest and oldest persons.
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

Page 17 11/2/2008
Object Deletion – Approach 1
int delIdx = 1;
Delete
DeletePerson
PersonBBby by
A
A person[delIdx] = null; setting
setting the referenceinin
the reference
position
position11totonull.
null.

person person

0 1 2 3 0 1 2 3

AA BB CC DD AA CC DD

Before A
A is executed After A
A is executed
Page 18 11/2/2008
Object Deletion – Approach 2
int delIdx = 1, last = 3; Delete
DeletePerson
PersonBBby by
setting
setting the referenceinin
the reference
A
A person[delIndex] = person[last];
position
position11totothe
thelast
last
person[last] = null; person.
person.

person person

0 1 2 3 0 1 2 3

AA BB CC DD AA DD CC

Before A
A is executed After A
A is executed
Page 19 11/2/2008
Person Array Processing –
Sample 3
• Searching for a particular 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);
}

Page 20 11/2/2008
Passing Arrays to Methods - 1
Code A
A public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);

At A
A before searchMinimum
arrayOne
A.
A.Local
Localvariable
variable
number
numberdoes
does not
not
exist before the
exist before the
method
methodexecution
execution

State of
Memory

Page 21 11/2/2008
Passing Arrays to Methods - 2
Code public int searchMinimum(float[]
number))
minOne { B
B
= searchMinimum(arrayOne);

The address is copied at B


B
arrayOne number
B.
B.The
Thevalue
valueofofthe
the
argument,
argument,which
whichisis
ananaddress,
address,isiscopied
copied
totothe parameter.
the parameter.
State of
Memory

Page 22 11/2/2008
Passing Arrays to Methods - 3
Code public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);
… C
C
}

While at C
C inside the method

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

State of
Memory

Page 23 11/2/2008
Passing Arrays to Methods - 4
Code public int searchMinimum(float[]
number))
minOne {
= searchMinimum(arrayOne);

D
D
}

At D
D after searchMinimum
arrayOne number
D.
D.The
Theparameter
parameterisis
erased.
erased.TheTheargument
argument
still
still points to thesame
points to the same
object.
object.
State of
Memory

Page 24 11/2/2008

You might also like