Grouping Objects
Arrays and Arrays and forfor loops loops
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Fixed-Size Collections
• Sometimes the maximum collection Sometimes the maximum collection size is known.size is known.
• Programming languages usually Programming languages usually offer a special offer a special fixed-sizefixed-size collection collection type: the type: the arrayarray..
• Java arrays can store Java arrays can store objectsobjects or or primitive valuesprimitive values..
• Arrays use a special syntax.Arrays use a special syntax.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The weblog-analyzer Project
• A web server records details of each access.
• It supports webmaster tasks:• Most popular pages• Busiest periods• How much data is being delivered• Broken references
• It analyses accesses by hour.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Creating an Array Object
public class LogAnalyzerpublic class LogAnalyzer{{
private int[] hourCounts;private int[] hourCounts;
private LogfileReader reader;private LogfileReader reader; public LogAnalyzer()public LogAnalyzer() { { hourCounts = new int[24];hourCounts = new int[24]; reader = new LogfileReader();reader = new LogfileReader(); }}
......
}}
Array variable declarationArray variable declaration
Array object Array object constructionconstruction
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The The hourCountshourCounts Array Array
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Using an ArraySquare-bracketsSquare-brackets notation is used to notation is used to accessaccess an array element - e.g.an array element - e.g.
hourCounts[hour]hourCounts[hour]
where where hourhour must be an integer variable must be an integer variable holding a valid index to the holding a valid index to the hourCountshourCounts array array (0..23). (0..23). Array elements are used just like variables. Array elements are used just like variables. They can be assigned:They can be assigned:
hourCounts[hour] = 42;hourCounts[hour] = 42;
Or used in expressions:Or used in expressions:
adjusted = 2*(hourCounts[hour] - 3);adjusted = 2*(hourCounts[hour] - 3); System.out.println (hourCounts[hour]); System.out.println (hourCounts[hour]);
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] hourCounts;private int[] hourCounts;private Person[] students;private Person[] students;
...... hourCounts = new int[24];hourCounts = new int[24];students = new Person[100];students = new Person[100];
......
hourcounts[i] = 0;hourcounts[i] = 0;students[j].enroll ("Co320-S");students[j].enroll ("Co320-S");System.out.println (hourcounts[i]);System.out.println (hourcounts[i]);
declarationdeclaration
constructionconstruction
useuse
Using an Array
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Special Syntax for Array Literals
private int[] numbers = {3, 15, 4, 5};private int[] numbers = {3, 15, 4, 5};
......
System.out.println (numbers[i]);System.out.println (numbers[i]);
declaration declaration and and
initialisationinitialisation
Array literals can only be used in Array literals can only be used in initialisationsinitialisations
Array literals can only be used in Array literals can only be used in initialisationsinitialisations
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Array literals can only be used in Array literals can only be used in initialisationsinitialisations
Array literals can only be used in Array literals can only be used in initialisationsinitialisations
Note: ‘Note: ‘lengthlength’ is a ’ is a fieldfield of the array object of the array objectNote: ‘Note: ‘lengthlength’ is a ’ is a fieldfield of the array object of the array object
Special Syntax for Array Literals
private int[] numbers = {3, 15, 4, 5};private int[] numbers = {3, 15, 4, 5};
......
int n = numbers.length;int n = numbers.length;
Unlike ‘Unlike ‘length()length()’, which is a ’, which is a methodmethod of of StringStringUnlike ‘Unlike ‘length()length()’, which is a ’, which is a methodmethod of of StringString
no brackets!no brackets!
declaration declaration and and
initialisationinitialisation
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Unlike ‘Unlike ‘length()length()’, which is a ’, which is a methodmethod of of StringStringUnlike ‘Unlike ‘length()length()’, which is a ’, which is a methodmethod of of StringString
Array literals can only be used in Array literals can only be used in initialisationsinitialisations
Array literals can only be used in Array literals can only be used in initialisationsinitialisations
Note: ‘Note: ‘lengthlength’ is a ’ is a fieldfield of the array object of the array objectNote: ‘Note: ‘lengthlength’ is a ’ is a fieldfield of the array object of the array object
Special Syntax for Array Literals
private int[] numbers = {3, 15, 4, 5};private int[] numbers = {3, 15, 4, 5};
......
int n = numbers.length;int n = numbers.length;
Unlike ‘Unlike ‘size()size()’, which is a ’, which is a methodmethod of of ArrayListArrayListUnlike ‘Unlike ‘size()size()’, which is a ’, which is a methodmethod of of ArrayListArrayList
no brackets!no brackets!
declaration declaration and and
initialisationinitialisation
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The for Loop
• There are two variations of the for There are two variations of the for loop, loop, for-eachfor-each (already seen) and (already seen) and forfor..
• The The forfor loop is often used to iterate a loop is often used to iterate a fixed numberfixed number of times. of times.
• It is usually used with a It is usually used with a control control variablevariable that changes a that changes a fixed amountfixed amount on each iteration.on each iteration.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Structure of the for Loop
for (for (initialisationinitialisation; ; conditioncondition; ; post-body actionpost-body action) {) { ... loop body... loop body}}
Equivalent Equivalent while-loopwhile-loop form: form:
initialisation;while (condition) { ... loop body... loop body ... post-body action}
loop headerloop header
Statement(s) to be repeatedStatement(s) to be repeated
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
An Example
for (for (int hour = 0int hour = 0; ; hour < hourCounts.lengthhour < hourCounts.length; ; hour++hour++) {) { System.out.println (hour + ": " + hourCounts[hour]);System.out.println (hour + ": " + hourCounts[hour]);}}
int hour = 0;int hour = 0;while (while (hour < hourCounts.lengthhour < hourCounts.length) {) { System.out.println(hour + ": " + hourCounts[hour]);System.out.println(hour + ": " + hourCounts[hour]); hour++;hour++;}}
for loop versionfor loop version
while loop versionwhile loop version
Note: variableNote: variable hourhour no longer exists here …no longer exists here …Note: variableNote: variable hourhour no longer exists here …no longer exists here …
Note: variableNote: variable hourhour still exists here …still exists here …Note: variableNote: variable hourhour still exists here …still exists here …
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int[] numbers = {4, 1, 22, 9, 14, 3, 9};int[] numbers = {4, 1, 22, 9, 14, 3, 9};
for ( ... ) {for ( ... ) { ... ...}}
Practice
Given an array of numbers, print out all the numbers Given an array of numbers, print out all the numbers in the array – one number per line. Use a in the array – one number per line. Use a forfor loop: loop:Given an array of numbers, print out all the numbers Given an array of numbers, print out all the numbers in the array – one number per line. Use a in the array – one number per line. Use a forfor loop: loop:
Write this now!Write this now!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int[] numbers = {4, 1, 22, 9, 14, 3, 9};int[] numbers = {4, 1, 22, 9, 14, 3, 9};
for ( ... ) {for ( ... ) { ... ...}}
Practice
Given an array of numbers, print out all the numbers Given an array of numbers, print out all the numbers in the array – one number per line. Use a in the array – one number per line. Use a forfor loop: loop:Given an array of numbers, print out all the numbers Given an array of numbers, print out all the numbers in the array – one number per line. Use a in the array – one number per line. Use a forfor loop: loop:
int[] numbers = {4, 1, 22, 9, 14, 3, 9};int[] numbers = {4, 1, 22, 9, 14, 3, 9};
for (for (int i = 0int i = 0; ; i < i < numbersnumbers.length.length; ; i++i++) ) {{ System.out.println (numbers[i]);System.out.println (numbers[i]);}}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Given an array of numbers, print out all the numbers Given an array of numbers, print out all the numbers in the array – one number per line. Use a in the array – one number per line. Use a forfor loop: loop:Given an array of numbers, print out all the numbers Given an array of numbers, print out all the numbers in the array – one number per line. Use a in the array – one number per line. Use a forfor loop: loop:Actually, Actually, arraysarrays also count as also count as collectionscollections – so we – so we can use a can use a for-eachfor-each loop on them:loop on them:Actually, Actually, arraysarrays also count as also count as collectionscollections – so we – so we can use a can use a for-eachfor-each loop on them:loop on them:
int[] numbers = {4, 1, 22, 9, 14, 3, 9};int[] numbers = {4, 1, 22, 9, 14, 3, 9};
for (for (int i = 0int i = 0; ; i < i < numbersnumbers.length.length; ; i++i++) ) {{ System.out.println (numbers[i]);System.out.println (numbers[i]);}}
Practice
for (for (int n :int n : numbersnumbers) ) {{ System.out.println (System.out.println (nn););}}
simpler!!!
simpler!!!
simpler!!!
simpler!!!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for (for (int n :int n : numbersnumbers) ) {{ System.out.println (System.out.println (nn););}}
Warning !!!
Collection (or array) elements accessed through a Collection (or array) elements accessed through a for-eachfor-each loop are loop are copiescopies of the actual elements: of the actual elements:Collection (or array) elements accessed through a Collection (or array) elements accessed through a for-eachfor-each loop are loop are copiescopies of the actual elements: of the actual elements:
Works
Works
Works
Works
But don’t try assigning to them:But don’t try assigning to them:But don’t try assigning to them:But don’t try assigning to them:
for (for (int n :int n : numbersnumbers) ) {{ n = 2*n;n = 2*n;}}
ChangesChanges copiescopies of elements inof elements in
numbersnumbers – does not change any of the – does not change any of the elements in elements in numbersnumbers itself!itself!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Warning !!!
But don’t try assigning to them:But don’t try assigning to them:But don’t try assigning to them:But don’t try assigning to them:
for (for (int n :int n : numbersnumbers) ) {{ n = 2*n;n = 2*n;}}
ChangesChanges copiescopies of elements inof elements in
numbersnumbers – does not change any of the – does not change any of the elements in elements in numbersnumbers itself!itself!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Warning !!!But don’t try assigning to them:But don’t try assigning to them:But don’t try assigning to them:But don’t try assigning to them:
for (for (int n :int n : numbersnumbers) ) {{ n = 2*n;n = 2*n;}}
ChangesChanges copiescopies of elements inof elements in
numbersnumbers – does not change any of the – does not change any of the elements in elements in numbersnumbers itself!itself!
To do this, we must use a To do this, we must use a forfor loop:loop:To do this, we must use a To do this, we must use a forfor loop:loop:
for (for (int i = 0int i = 0; ; i < i < numbersnumbers.length.length; ; i++i++) ) {{ numbers[i] = 2*numbers[i];numbers[i] = 2*numbers[i];}}
ChangesChanges the elements in the elements in numbersnumbers itself!itself!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int[] fib = new int[100];int[] fib = new int[100];
fib[0] = 0; fib[1] = 1;fib[0] = 0; fib[1] = 1;
for ( ... ) {for ( ... ) { ... ...}}
Fibonacci:Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...(each number is the sum of the previous two numbers)(each number is the sum of the previous two numbers)(start with zero and one)(start with zero and one)
Fibonacci:Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...(each number is the sum of the previous two numbers)(each number is the sum of the previous two numbers)(start with zero and one)(start with zero and one)
PracticeFill an array with the first 100 numbers of Fill an array with the first 100 numbers of thethe FibonacciFibonacci sequencesequence..Fill an array with the first 100 numbers of Fill an array with the first 100 numbers of thethe FibonacciFibonacci sequencesequence..
Write this now!Write this now!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int[] fib = new int[100];int[] fib = new int[100];
fib[0] = 0; fib[1] = 1;fib[0] = 0; fib[1] = 1;
for ( ... ) {for ( ... ) { ... ...}}
Fibonacci:Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...(each number is the sum of the previous two numbers)(each number is the sum of the previous two numbers)(start with zero and one)(start with zero and one)
Fibonacci:Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...(each number is the sum of the previous two numbers)(each number is the sum of the previous two numbers)(start with zero and one)(start with zero and one)
PracticeFill an array with the first 100 numbers of Fill an array with the first 100 numbers of thethe FibonacciFibonacci sequencesequence..Fill an array with the first 100 numbers of Fill an array with the first 100 numbers of thethe FibonacciFibonacci sequencesequence..
int[] fib = new int[100];int[] fib = new int[100];
fib[0] = 0; fib[1] = 1;fib[0] = 0; fib[1] = 1;
for (for (int i = 2int i = 2; ; i < i < fibfib.length.length; ; i++i++) {) { fib[i] = fib[i-2] + fib[i-1];fib[i] = fib[i-2] + fib[i-1];}}
Cannot be written Cannot be written with a with a for-eachfor-each looploop..
Cannot be written Cannot be written with a with a for-eachfor-each looploop..
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for loops can haveany size of increment
// Print multiples of 3 that are below 40.// Print multiples of 3 that are below 40.
for (for (int num = 3;int num = 3; num < 40;num < 40; num = num + 3num = num + 3) {) {
System.out.println (num);System.out.println (num);
}}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
whilewhile loop without a loop without a collectioncollection
int index = 0;int index = 0;while (while (index <= 42index <= 42) {) { System.out.println (index);System.out.println (index); index = index + 2;index = index + 2;}}
int index = 0;int index = 0;while (while (index >= 42index >= 42) {) { System.out.println (index);System.out.println (index); index = index + 2;index = index + 2;}}
int index = 0;int index = 0;while (while (index <= 42index <= 42) {) { System.out.println (index);System.out.println (index); index = index - 2;index = index - 2;}}
// Print all even numbers from 0 to 42 inclusive.// Print all even numbers from 0 to 42 inclusive.
// Programming error? This does nothing at all!// Programming error? This does nothing at all!
// Programming error? This loop never ends!// Programming error? This loop never ends!
Seen Seen before
before
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The same – but withThe same – but with for for loopsloops
for (for (int index = 0int index = 0; ; index <= 42index <= 42;; index = index + 2index = index + 2) ) {{ System.out.println (index);System.out.println (index);}}
for (for (int index = 0int index = 0; ; index >= 42index >= 42;; index = index + 2index = index + 2) {) { System.out.println (index);System.out.println (index);}}
for (for (int index = 0int index = 0; ; index <= 42index <= 42;; index = index - 2index = index - 2) {) { System.out.println (index);System.out.println (index);}}
// Print all even numbers from 0 to 42 inclusive.// Print all even numbers from 0 to 42 inclusive.
// Programming error? This does nothing at all!// Programming error? This does nothing at all!
// Programming error? This loop never ends!// Programming error? This loop never ends!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
for loops can exit early
/**/** * Search an array for a zero. * Search an array for a zero. * * * @return The index of the first zero element * @return The index of the first zero element * (if none found, return -1) * (if none found, return -1) */*/public int findZero (int[] A)public int findZero (int[] A){{ for (for (int i = 0int i = 0; ; i < i < numbersnumbers.length.length; ; i++i++) ) {{ if (numbers[i] == 0) {if (numbers[i] == 0) { return i;return i; } } }} return -1;return -1;} }
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Review
• ArraysArrays are appropriate where a fixed-size are appropriate where a fixed-size collection is required.collection is required.
• ArraysArrays use special use special [square brackets] [square brackets] syntax.syntax.
• ForFor loops are a better alternative to loops are a better alternative to whilewhile loops loops when the number of repetitions is known.when the number of repetitions is known.
• ForFor loops are often used to loops are often used to introduceintroduce and and controlcontrol an an index variableindex variable when iterating when iterating through through arraysarrays..
• ForFor loops can exit early (with a loops can exit early (with a returnreturn).).