W1 Chapter Revision Array
W1 Chapter Revision Array
W1 Chapter Revision Array
Week 3
Arrays Revision
1
Lecture Outline
• Review the Arrays
• Define and create Arrays of Objects
• Two-Dimensional Arrays
2
Learning Objectives
• To define and use arrays for basic data
organization.
• To discuss the issues related to arrays as objects
and array of objects.
• To create and use multidimensional arrays.
Array
• Consider the following program (input underlined):
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.57142857142857
4 days were above average.
• We need the temperatures to compute the average, and again to tell how
many were above average.
4
Array
• 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
Arrays
• array: A variable that stores many values of the same type.
– element: One value in an array.
– index: A 0-based integer used to access an element from
an array.
• We usually draw an array as a row or column of boxes.
– Example: an array of ten integers
index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3
• Example
Variation 1 Variation 2
int[ ] numbers; int numbers[ ];
numbers = new int[7]; numbers = new int[7];
Array auto-initialization
• When arrays are initially constructed, every element is automatically initialized
to a "zero-equivalent" value.
– int: 0
– double: 0.0
– boolean: false
– char: '\0' (the "null character")
– String or object: null (null means "no object")
An array of integers
inde 0 1 2 3 4
x
value 0 0 0 0 0
inde
An array of real numbers 0 1 2 3
x
value 0.0 0.0 0.0 0.0 8
Accessing array elements
• Assigning a value to an array element:
<array name> [ <index> ] = <value> ;
– Example:
numbers[0] = 27;
numbers[3] = -6;
index 0 1 2 3 4 5 6 7 8 9
value 27 0 0 -6 0 0 0 0 0 0
9
Accessing array elements
• Using an array element's value in an expression:
<array name> [ <index> ]
– Example:
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("Element 3 is
negative.");
} numbers[3]
index 0 1 2 3 4 5 6 7 8 9
value 27 0 0 -6 0 0 0 0 0 0
10
Out-of-bounds indexes
• The indexes that are legal to access in an array are those in the range of 0
to the array's length - 1.
– Reading or writing any index outside this range will throw an
ArrayIndexOutOfBoundsException.
• Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[-1]); // exception
System.out.println(data[9]); // okay
System.out.println(data[10]); // exception
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
11
Arrays of other types
• Arrays can contain other types, such as double.
– Example:
double[] results = new double[6];
results[2] = 3.4;
results[5] = -0.5;
inde 0 1 2 3 4 5
x
value 0.0 0.0 3.4 0.0 0.0 -0.5
– Example:
boolean[] tests = new boolean[6];
tests[3] = true;
inde 0 1 2 3 4 5
x 12
Arrays and for loops
• Arrays are very commonly used with for loops that pass over
each element and process it in some way:
13
More arrays and for loops
• Sometimes we assign each array element a value in a for loop.
– Example:
for (int i = 0; i < 8; i++) {
numbers[i] = 2 * i;
} index 0 1 2 3 4 5 6 7 numbers
value 0 2 4 6 8 10 12 14
• What values would be stored into the array after this code?
for (int i = 0; i < 8; i++) {
numbers[i] = i * i;
}
value 0 1 4 9 16 25 36 49
14
The .length field
• An array's length field stores its number of elements.
– General syntax:
<array name> .length
15
Why are arrays useful?
• Arrays store a large amount of data in one variable.
– Example: Read in a file of 1000 numbers, then print out the numbers in
reverse order.
16
Array initialization statement
• Quick array initialization, general syntax:
<type> [] <name> = {<value>, <value>, ..., <value>};
– Example:
int[] numbers = {12, 49, -2, 26, 5, 17, -6};
index 0 1 2 3 4 5 6
value 12 49 -2 26 5 17 -6
– This syntax is useful when you know in advance what the array's element values will be.
– You don't explicitly specify the array's size in this syntax.
• The Java compiler figures out the size by looking at the number of values written between { and }.
17
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 };
number.length 4
samplingData.length 9
monthName.length 12
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 an array = “)
size= Integer.parseInt(input.readLine());
number = new int[size];
Array practice problem
• What element values are stored in the following array?
index 0 1 2 3 4 5 6
value 2 7 8 14 28 35 44
20
The Arrays class
• The Arrays class in package java.util has several useful static
methods for manipulating arrays:
– Example:
int[] a = {2, 5, 1, 6, 14, 7, 9};
for (int i = 1; i < a.length; i++) {
a[i] += a[i - 1];
}
System.out.println("a is " + Arrays.toString(a));
Output:
a is [2, 7, 8, 14, 28, 35, 44]
22
Weather problem
23
Weather solution
// This program reads several days' temperatures from the user
// and computes the average and how many days were above average.
import java.util.*;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
int[] temperatures = new int[days]; // array to store days' temperatures
int sum = 0;
for (int i = 0; i < days; i++) { // read/store each day's temperature
System.out.print("Day " + (i + 1) + "'s high temp: ");
temperatures[i] = console.nextInt();
sum += temperatures[i];
}
double average = (double) sum / days;
int count = 0; // see if each day is above average
for (int i = 0; i < days; i++) {
if (temperatures[i] > average) {
count++;
}
}
// report results
System.out.println("Average temp = " + average);
System.out.println(count + " days above average");
}
}
24
Rainfall Solution
• Create an array to store rainfall data in a month.
double[] rainfall = new double[12];
rainfall
0 1 2 3 4 5 6 7 8 9 10 11
28
Array Operation: Printing array elements
• Example (print each element of an array on a line):
int[] list = {4, 1, 9, 7};
for (int i = 0; i < list.length; i++) {
System.out.println(i + ": " + list[i]);
}
Output:
0: 4
1: 1
2: 9
3: 7
• How could we change the code to print the following?
4, 1, 9, 7
(Do not use Arrays.toString.)
29
Array Operation: Examining array elements
• Example (find the largest even integer in an array):
int[] list = {4, 1, 2, 7, 6, 3, 2, 4, 0, 9};
int largestEven = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] % 2 == 0 && list[i] > largestEven) {
largestEven = list[i];
}
}
System.out.println("Largest even: " + largestEven);
Output:
Largest even: 6
30
Using Array Element as Parameters
double n = 0.0;
double[] a = {2.3, 4.5, 6.7, 8.9};
int i = 2;
31
Arrays as parameters
• Arrays are objects.
– When they are passed as parameters, they are passed by reference.
– Changes made in the method will also be seen by the caller.
– Example:
public static void main(String[] args) {
int[] iq = {126, 167, 95};
System.out.println(Arrays.toString(iq));
doubleAll(iq);
System.out.println(Arrays.toString(iq));
}
public static void doubleAll(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = 2 * array[i];
}
}
– Output:
[126, 167, 95]
[252, 334, 190]
32
Arrays as parameters
• An array can be passed as a parameter.
– Syntax (declaration):
public static <type> <name>(<type>[] <name>) {
– Example:
public static double average(int[] numbers) {
– Syntax (call):
<method name>(<array name>);
– Example:
int[] scores = {13, 17, 12, 15, 11};
double avg = average(scores);
33
Array parameter: example
• Array as parameter example:
public static void main(String[] args) {
int[] iq = {126, 167, 95};
int result = max(iq);
System.out.println("Max = " + result);
}
public static int max(int[] array) {
int largest = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
return largest;
}
• Output:
Max = 167
34
Array parameter diagram
iq
public static void main(String[] args) {
int[] iq = 126, 167, 95};
System.out.println(Arrays.toString(iq));
doubleAll(iq);
System.out.println(Arrays.toString(iq));
}
array
public static void doubleAll(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = 2 * array[i];
}
}
– Output:
[126, 167, 95]
[252, 334, 190]
index 0 1 2
value 126
252 167
334 190
95
35
Arrays as return values
• An array can also be returned from a method.
– Syntax (declaration):
public static <type>[] <name>(<parameters>) {
– Example:
public static int[] readAllNumbers(Scanner input) {
– Syntax (call):
<type>[] <name> = <method name>(<parameters>);
– Example:
Scanner fileScan = new Scanner(new
File("weather.dat"));
int[] numbers = readAllNumbers(fileScan);
36
Array return example
public static void main(String[] args) {
int a = 100;
int[] numbers = initArray(a);
System.out.println(Arrays.toString(numbers));
}
37
Array parameter: Exercise
• Write a method named average that accepts an array of
integers as its parameter and returns the average of the
values in the array.
• Write a method named contains that accepts an array of
integers and a target integer value as its parameters and
returns whether the array contains the target value as one of
its elements.
• Write a method named roundAll that accepts an array of
doubles as its parameter and modifies each element of the
array so that it is rounded to the nearest whole number.
38
Array parameter: Solutions
public static double average(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public static boolean contains(int[] values, int target) {
for (int i = 0; i < values.length; i++) {
if (values[i] == target) {
return true;
}
}
return false;
}
public static void roundAll(double[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = Math.round(array[i]);
}
}
39
Arrays of Objects
person
State
of
Memory
After AA is executed
Creating an Object Array
Code Person[ ] person; Now
Nowthe
thearray
arrayfor
forstoring
storing20
20
Person objects is created,
Person objects is created,
BB person = new Person[20]; but
butthe
thePerson
Personobjects
objects
themselves
themselves are notyet
are not yet
person[0] = new Person( );
created.
created.
person
0 1 2 3 4 16 17 18 19
State
of
Memory
After BB is executed
Creating an Object Array
Code Person[ ] person;
One
OnePerson
Personobject
objectisiscreated
created
person = new Person[20]; and the reference to this
and the reference to this
object
objectisisplaced
placedininposition
position0.0.
CC person[0] = new Person( );
person
0 1 2 3 4 16 17 18 19
State
of Person
Memory
After CC is executed
Creating an Object Array
Code for(int i=0;i<Person.length;i++) 2020Person
Personobjects
objectsareare
D
D person[i] = new Person( );
created
to
and the reference
created and the reference
tothese
theseobjects
objectsare
areplaced
placed
ininposition 0 to 19.
position 0 to 19.
person After D
D is executed
0 1 2 3 4 16 17 18 19
State
of
Person
Person
Person
Person
Person
Person
Person
Person
Person
Memory
Array of Object - Sample
public class Rectangle
{
private int length,width,area;
} // end class
Array of Object- Sample
import java.util.*;
public class TestRectangle{
public static void main (String []args)
{
static Scanner console = new Scanner(System.in);
Rectangle rect[]=new Rectangle[2];
for (int j=0;j<rect.length;j++){
System.out.print("Length : ");
int length = console.nextInt();
System.out.print("Width: ");
int width = console.nextInt();
rect[j]=new Rectangle(length,width);
rect[j].calculateArea();
System.out.println("Area of Rectangle " + (j+1) + " = " +
rect[j].getArea());
System.out.println();
}
}
}//end class
Array of Object- Sample
import java.io.*;
class Person
{
private String name;
private int age;
private char gender;
} // end PersonList
Array of Object- Sample
import java.util.*;
public class TestPerson {
public static void main(String[] arg){
Scanner read = new Scanner(System.in);
String name=null;
int age;
char gender;
System.out.println("Enter number of person: ");
int num = read.nextInt();
PersonList people = new PersonList(num);
System.out.println("\n");
for (int i= 0; i< num; i++) {
System.out.print("\nEnter name = ");
name = read.next();
System.out.print("Enter age = ");
age = read.nextInt();
System.out.print("Enter gender = ");
gender = read.nextLine().charAt(0);
people.addRecord(name,age,gender);
}
people.displayRecord();
}
} // end TestPerson
Array of Object- Sample
Output:
Enter number of person: 2
Delete
DeletePerson
PersonBBbybysetting
setting
AA int delIdx = 1; the
the reference in position11toto
reference in position
person[delIdx] = null; null.
null.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA CC DD
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA DD CC
int i = 0;
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);
}
Array of Object- Sample
Object Deletion – Approach 1
Delete
DeletePerson
PersonBBbybysetting
AA int delIdx = 1; the
setting
the reference in position11toto
reference in position
person[delIdx] = null; null.
null.
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA CC DD
person person
0 1 2 3 0 1 2 3
AA BB CC DD AA DD CC
payScaleTable
0 1 2 3 4
double[][] payScaleTable; 0
payScaleTable 1
= new double[4][5];
2
3
Two-dimensional Arrays
• An element in a two-dimensional array is accessed by
its row and column index.
Two-dimensional Arrays
• Find the average of each row.
average[i] += payScaleTable[i][j];
}
int row;
int column;
matrix
Two-dimensional Arrays
Print
Read Data
Sum by Column
value 3 8 9 7 5
index 0 1 2 3 4
After: value 8 9 7 5 3
– Shifting elements is useful when inserting and removing values from arrays
after they have already been filled with data.
70
Excercise2: Shifting Element
• A left shift of the elements of an array:
index 0 1 2 3 4
value 3 8 9 7 5
index 0 1 2 3 4
value 8 9 7 5 3
71
Exercise: The 2-Dimensional Array grade
Write a Java program that meet the requirements as in Display 6.19:
72
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.
Malik, D. S. (2006). Java Programming: from Problem Analysis
to Program Design, Thomson Course Tech.
Conclusion
Q & A Session
74