SlideShare a Scribd company logo
Modified by
Martin Chapman
4CCS1PRP, Programming Practice 2012
Lecture 6: Arrays - Part 1
Java for Everyone by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.
Slides by Donald W. Smith
TechNeTrain.com
Martin Chapman
Contents
 Arrays
 The Enhanced for Loop
 Common Array Algorithms
 Using Arrays with Methods
 Two-Dimensional Arrays
 Array Lists
Chapter Goals
 To become familiar with using arrays and
array lists to collect values
 To use the enhanced for loop for traversing
arrays and array lists
 To learn about common algorithms for
processing arrays and array lists
 To learn how to use two-dimensional arrays
In this chapter, you will learn about
arrays, array lists, and common
algorithms for processing them.
1. Why do we need arrays?
Sequences of Values
‣ A Computer Program often needs to
store a list of values and then process
them.
‣ For example, to find the highest.
‣ Say you had this list of values, how
many variables would you need?
‣ double input1, input2, input3….
‣ Impractical for manipulation;
unnecessary code replication.
An Example
beer Carlsberg, Guinness, Budweiser
An Example
if ( Carlsberg.alcoholPercentage is >= 5 )
then
My head hurts
otherwise
In for work at 9am
end
if ( Guinness.alcoholPercentage is >= 5 )
then
My head hurts
otherwise
In for work at 9am
end
if ( Budweiser.alcoholPercentage is >= 5 )
then
...
Only a ‘pseudocode’ example
beer Carlsberg, Guinness, Budweiser
Arrays
‣ Are the answer!
An array collects sequences of values of the
same type.
2. Array Syntax
Declaring an Array
 Declaring an array is a two step process.
1) double[] data; // declare array variable
2) data = new double[10]; // initialise size
You cannot use the array
until you tell the compiler
the size of the array in
step 2.
Declaring an Array (Step 1)
 Make a named ‘list’ with the following parts:
Type Square Braces Array name semicolon
double
 [ ] data ;
 You are declaring that
• There is an array named data
• The elements inside are of type double
• You have not (YET) declared how many elements
are in inside
 Other Rules:
 Arrays can be declared anywhere you can declare a
variable
 Do not use ‘reserved’ words or already used names
Declaring an Array (Step 2)
data
[0] [1] [2] [3] [4] … [9]
double double double double double double
 Reserve memory for all of the elements:
Array name Keyword Type Size semicolon
data = new double [10] ;
 You are reserving memory for:
• The array named data
• Needs storage for [10]
• Elements the size of type double
 You are also setting up the array variable
 Now the compiler knows how many elements there are
Common Error 1
double[] data;
...
data[0] = 29.95; // Error—data not initialised
 Uninitialised Arrays
 Don’t forget to allocate the array contents!
 The compiler will catch this error data
0
1
2
3
4
5
6
7
8
9
double[] data;
data = new double[10];
data[0] = 29.95; // No error
Error: D:JavaUnitialised.java:7:
variable data might not have been initialized
One Step Array Declaration
 Declare and Create at the same time:
Type Braces Array name Keyword Type Size semi
double [] data = new double [10] ;
 You are declaring that
• There is an array named data
• The elements inside are of type double
 You are reserving memory for the array
• Needs storage for [10]
• Elements the size of type double
 You are also setting up the array variable
Declaring and Initialising an Array
 You can declare and set the initial contents of all
elements by:
Type Braces Array name contents list semi
int
 [ ] primes = { 2, 3, 5, 7} ;
 You are declaring that
 There is an array named primes
 The elements inside are of type int
 Reserve space for four elements
• No need for ‘new’ keyword, the compiler counts
them for you.
 Set initial values to 2, 3, 5, and 7
 Note the curly braces around the contents list
3. Accessing Arrays
Accessing Array Elements
 Each element is numbered
 We call this the ‘index’
 Access an element by:
• Name of the array
• Index number
data[i]
public static void main(String[] args)
{
double data[];
data = new double[10];
data[4] = 35;
System.out.println(data[4]);
}
Elements in the array data are
accessed by an integer index i,
using the notation data[i].
The last element is at index 9:
Array Index Numbers
 Array index numbers start at 0
 The rest are positive integers
 A 10 element array has indexes 0 through 9
 There is NO element 10!
public static void main(String[] args)
{
double data[];
data = new double[10];
}
The first element is at index 0:
Problem: Common Error 2
 Array Bounds Errors
 Accessing a nonexistent element is very common error
 Array indexing starts at 0
 Your program will stop at run time
public class OutOfBounds
{
public static void main(String[] args)
{
double data[];
data = new double[10];
data[10] = 100;
}
}
java.lang.ArrayIndexOutOfBoundsException: 10

 at OutOfBounds.main(OutOfBounds.java:7)
The is no element 10:
Solution: Array Bounds Checking
 An array knows how many elements it can hold
 data.length is the size of the array named data
 It is an integer value (index of the last element + 1)
 Use this to range check and prevent bounds errors
public static void main(String[] args)
{
int i = 10, value = 34;
double data[];
data = new double[10];
if (0 <= i && i < data.length) // value is 10
{
data[i] = value;
}
}
Visiting Array Elements
 An array knows how many elements it can hold
 data.length is the size of the array named data
 It is an integer value (index of the last element + 1)
 Similarly, use this to visit all the elements in an array.
public static void main(String[] args)
{
int[ ] data = { 1 , 2 , 3 , 4 , 5 };
for ( int i = 0; i < data.length; i++ )
{
System.out.println( data[ i ] );
}
}
 The benefits of using an array:
Back to Beer...
beer array = { Carlsberg, Guinness, Budweiser }
Set variable i = 0;
Loop until i == length of beer array
if element at i alcoholContent is > 5
then
My head hurts
otherwise
In for work at 9am
end
increase i by 1.
Next Loop.
A significant decrease in code.
To recap...
Array Syntax Review
 To declare an array, specify the:
 Array variable name
 Element Type
 Length (number of elements)
Summary: Declaring Arrays
4. Array Limitations
Problems?
double[] inputs = new double[ ? ];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
Problems?
double[] inputs = new double[ ? ];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
double[] inputs = new double[100];
while (in.hasNextDouble())
{
inputs[ ? ] = in.nextDouble();
}
Problems?
for (int i = 0; i < ? ; i++)
{
System.out.println(data[i]);
}
Partially-Filled Arrays
 An array cannot change size at run time
 The programmer may need to guess at the maximum
number of elements required
 It is a good idea to use a constant for the size chosen
 A partial solution?
 Use a variable to track how many elements are filled
Partially-Filled Arrays
final int LENGTH = 100;
double[] data = new double[LENGTH];
int currentSize = 0;
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
if (currentSize < data.length)
{
data[currentSize] = in.nextDouble();
currentSize++;
}
}
Use the .length value
and currentSize
variable to prevent
over-filling the array
‘Walking’ a Partially Filled Array
for (int i = 0; i < currentSize; i++)
{
System.out.println(data[i]);
}
A for loop is a natural choice
to walk through an array
‣ Use currentSize, not data.length for the last element
 Using for loops to ‘walk’ arrays is very common
 The enhanced for loop simplifies the process
 Also called the “for each” loop
 Read this code as:
• “For each element in data”
double[] data = . . .;
double sum = 0;
for (double element : data)
{
sum = sum + element;
}
A shortcut: The Enhanced for Loop
 As the loop proceeds, it will:
 Access each element in order (0 to length -1)
 Copy it to the element variable
 Execute loop body
 Not possible to:
 Change elements
 Get bounds error
double[] data = . . .;
double sum = 0;
for (double element : data)
{
sum = sum + element;
}
A shortcut: The Enhanced for Loop
Syntax: The “for each” loop
 Use the “for each” loop when:
 You need to access every element in the array
 You do not need to change any elements of the array
Common Array Algorithms
 Practical array implementations:
 Filling an Array
 Sum and Average Values
 Maximum and Minimum
 Output Elements with Separators
 Linear Search
 Removing an Element
 Inserting an Element
 Copying Arrays
 Reading Input
Common Algorithms 1:
1) Filling an Array
 Initialise an array to a set of calculated values
 Example: Fill an array with squares of 0 through 10
int[] squares = new int[11];
for (int i = 0; i < squares.length; i++)
{
squares[i] = i * i;
}
Common Algorithms 2:
2) Sum and Average
 Use ‘for each’ loop, and make sure not to divide by zero
double total = 0, average = 0;
for (double element : data)
{
total = total + element;
}
if (data.length > 0) { average = total / data.length; }
Common Algorithms 3:
double largest = data[0];
for (int i = 1; i < data.length; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
}
double largest = data[0];
for (double element : data)
{
if (element > largest)
largest = element;
}
 Maximum and Minimum
 Set largest to first element
 Use for or a ‘for each’ loop
 Use the same logic for minimum
double smallest = data[0];
for (double element : data)
{
if (element < smallest)
smallest = element;
}
Typical for loop to find maximum
‘for each’ to find maximum ‘for each’ to find minimum
 Element Separators
 Output all elements with separators between them
 No separator before the first or after the last element
 Handy Array method: Arrays.toString()
 Useful for debugging!
Common Algorithms 4:
for (int i = 0; i < data.length; i++)
{
if (i > 0)
{
System.out.print(" | ");
}
System.out.print(data[i]);
}
import java.util.*;
System.out.println(Arrays.toString(data));
Common Algorithms 5:
 Linear Search
 Search for a specific value in an array
 Start from the beginning (left), stop if/when it is found
 Uses a boolean ‘found’ flag to stop loop if found
int searchedValue = 100;
int pos = 0;
boolean found = false;
while (pos < data.length && !found)
{
if (data[pos] == searchedValue) {
found = true; }
else {
pos++; }
if (found) {
System.out.println(“Found at position: ” + pos); }
else {
System.out.println(“Not found”); }
}
Compound condition to prevent
bounds error if value not found.
Common Algorithms 6:
 Removing an element (at a given position)
 Requires tracking the ‘current size’ (# of valid elements)
 But don’t leave a ‘hole’ in the array!
 Solution depends on if you have to maintain ‘order’
• If not, find the last valid element, copy over position, update size
data[pos] = data[currentSize – 1];
currentSize--;
Common Algorithms 6:
 Removing an element (at a given position)
 Requires tracking the ‘current size’ (# of valid elements)
 But don’t leave a ‘hole’ in the array!
 Solution depends on if you have to maintain ‘order’
• If so, move all of the valid elements after ‘pos’ up one spot,
update size
for (int i = pos; i < currentSize - 1; i++)
{
data[i] = data[i + 1];
}
currentSize--;
Common Algorithms 7:
 Inserting an Element
 Solution depends on if you have to maintain ‘order’
• If so, find the right spot for the new element, move all of the
valid elements after ‘pos’ down one spot, insert the new
element, and update size
• If not, just add it to the end and update the size
if (currentSize < data.length)
{
for (int i = currentSize; i > pos; i--)
{
data[i] = data[i - 1];
}
data[pos] = newElement;
currentSize++;
}
Note: Array References
 Make sure you see the difference between the:
 Array variable: The named ‘handle’ to the array
 Array contents: Memory where the values are stored
int[] scores = { 10, 9, 7, 4, 5 };
An array variable contains a reference to the
array contents. The reference is the location
of the array contents (in memory).
Array variable Array contents
Reference
Values
Note: Array Aliases
 You can make one array reference refer to the
same contents of another:
int[] scores = { 10, 9, 7, 4, 5 };
Int[] values = scores; // Copying the array reference
An array variable specifies the location of
an array. Copying the reference yields a
second reference to the same array.
Array contents
References
Common Algorithms 8:
 Copying Arrays
 Not the same as copying only the reference
• Only have one actual set of contents!
Common Algorithms 8:
double[] data = new double[6];
. . . // Fill array
double[] prices = data; // Only a reference so far
double[] prices = Arrays.copyOf(data, data.length);
// copyOf creates the new copy, returns a reference
 Want to copy the contents of one array to another
 Use the Arrays.copyOf method
Common Algorithms 8:
 Growing an array
 Copy the contents of one array to a larger one
 Change the reference of the original to the larger one
 Example: Double the size of an existing array
 Use the Arrays.copyOf method
 Use ‘2 *’ in the second parameter
double[] values = new double[6];
. . . // Fill array
double[] newValues = Arrays.copyOf(values, 2 * values.length);
values = newValues;
Arrays.copyOf second parameter is
the length of the new array
Increasing the Size of an Array - Step 1
 Copy all elements of values to newValues
double[] newValues = Arrays.copyOf(values, 2 * values.length);
Increasing the Size of an Array - Step 2
 Then copy newValues reference over values
reference
values = newValues;
Common Algorithms 9:
 Reading Input
 Solution depends on if know how many values to expect
• If so, make an array of that size and fill it one-by-one
•
double[] inputs = new double[NUMBER_OF_INPUTS];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
Common Algorithms 9:
 Reading Input
 Solution depends on if know how many values to expect
• If so, make an array of that size and fill it one-by-one
• If not, make an array large enough for the maximum, and add
values to the end until no more are available.
double[] inputs = new double[NUMBER_OF_INPUTS];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
double[] inputs = new double[MAX_INPUTS];
int currentSize = 0;
while (in.hasNextDouble() && currentSize < inputs.length)
{
inputs[currentSize] = in.nextDouble();
currentSize++;
}
Common Algorithms 9:
double[] inputs = new double[INITIAL_SIZE];
int currentSize = 0;
while (in.hasNextDouble())
{
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
 Reading Input
 A better solution: double the array when it is full.
 Able to handle input of arbitrary length
LargestInArray.java (1)
Input values and store in next
available index of the array
LargestInArray.java (2)
Use a for loop and the
‘Find the largest’ algorithm
Common Error 3
 Underestimating the Size of the Data Set
 The programmer cannot know how someone might want
to use a program!
 Make sure that you write code that will politely reject
excess input if you used fixed size limits
Sorry, the number of lines of text is
higher than expected, and some could not be
processed. Please break your input into
smaller size segments (1000 lines maximum)
and run the program again.
Think you’re ahead?
Friday 2pm - 4pm, Lab S4.01
Objects, classes, data structures, GUIs...
martin.chapman@kcl.ac.uk
Feel like you’re behind?
Friday 2pm - 4pm, Lab S4.01
Cover all basic concepts.
martin.chapman@kcl.ac.uk

More Related Content

What's hot (20)

Methods in Java
Methods in JavaMethods in Java
Methods in Java
Jussi Pohjolainen
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Java arrays
Java arraysJava arrays
Java arrays
Jin Castor
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
Vikas Gupta
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
Hock Leng PUAH
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6
sumitbardhan
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Madishetty Prathibha
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
Padma Kannan
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6358 33 powerpoint-slides_6-strings_chapter-6
358 33 powerpoint-slides_6-strings_chapter-6
sumitbardhan
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
Padma Kannan
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 

Similar to An Introduction to Programming in Java: Arrays (20)

Array
ArrayArray
Array
PRN USM
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
12. arrays
12. arrays12. arrays
12. arrays
M H Buddhika Ariyaratne
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docxArraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
Victer Paul
 
9781111530532 ppt ch09
9781111530532 ppt ch099781111530532 ppt ch09
9781111530532 ppt ch09
Terry Yoast
 
Arrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.pptArrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
 
Array
ArrayArray
Array
Scott Donald
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
 
17-Arrays en java presentación documento
17-Arrays en java presentación documento17-Arrays en java presentación documento
17-Arrays en java presentación documento
DiegoGamboaSafla
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
MURADSANJOUM
 
Chap09
Chap09Chap09
Chap09
Terry Yoast
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
Vince Vo
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Arrays and Strings engineering education
Arrays and Strings engineering educationArrays and Strings engineering education
Arrays and Strings engineering education
csangani1
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docxArraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
Victer Paul
 
9781111530532 ppt ch09
9781111530532 ppt ch099781111530532 ppt ch09
9781111530532 ppt ch09
Terry Yoast
 
Arrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.pptArrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
 
17-Arrays en java presentación documento
17-Arrays en java presentación documento17-Arrays en java presentación documento
17-Arrays en java presentación documento
DiegoGamboaSafla
 
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdfJava R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
kamalabhushanamnokki
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
Vince Vo
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Arrays and Strings engineering education
Arrays and Strings engineering educationArrays and Strings engineering education
Arrays and Strings engineering education
csangani1
 
Ad

More from Martin Chapman (20)

Phenoflow: An Architecture for FAIRer Phenotypes
Phenoflow: An Architecture for FAIRer PhenotypesPhenoflow: An Architecture for FAIRer Phenotypes
Phenoflow: An Architecture for FAIRer Phenotypes
Martin Chapman
 
Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...
Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...
Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...
Martin Chapman
 
Principles of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learningPrinciples of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learning
Martin Chapman
 
Principles of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systemsPrinciples of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systems
Martin Chapman
 
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Martin Chapman
 
Technical Validation through Automated Testing
Technical Validation through Automated TestingTechnical Validation through Automated Testing
Technical Validation through Automated Testing
Martin Chapman
 
Scalable architectures for phenotype libraries
Scalable architectures for phenotype librariesScalable architectures for phenotype libraries
Scalable architectures for phenotype libraries
Martin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
Martin Chapman
 
Using AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patientsUsing AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patients
Martin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
Martin Chapman
 
Principles of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical softwarePrinciples of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical software
Martin Chapman
 
Principles of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical softwarePrinciples of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical software
Martin Chapman
 
Principles of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile healthPrinciples of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile health
Martin Chapman
 
Principles of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcarePrinciples of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcare
Martin Chapman
 
Principles of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systemsPrinciples of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systems
Martin Chapman
 
Principles of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledgePrinciples of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledge
Martin Chapman
 
Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...
Martin Chapman
 
Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...
Martin Chapman
 
Principles of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systemsPrinciples of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systems
Martin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
Martin Chapman
 
Phenoflow: An Architecture for FAIRer Phenotypes
Phenoflow: An Architecture for FAIRer PhenotypesPhenoflow: An Architecture for FAIRer Phenotypes
Phenoflow: An Architecture for FAIRer Phenotypes
Martin Chapman
 
Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...
Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...
Generating Computable Phenotype Intersection Metadata Using the Phenoflow Lib...
Martin Chapman
 
Principles of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learningPrinciples of Health Informatics: Artificial intelligence and machine learning
Principles of Health Informatics: Artificial intelligence and machine learning
Martin Chapman
 
Principles of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systemsPrinciples of Health Informatics: Clinical decision support systems
Principles of Health Informatics: Clinical decision support systems
Martin Chapman
 
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Mechanisms for Integrating Real Data into Search Game Simulations: An Applica...
Martin Chapman
 
Technical Validation through Automated Testing
Technical Validation through Automated TestingTechnical Validation through Automated Testing
Technical Validation through Automated Testing
Martin Chapman
 
Scalable architectures for phenotype libraries
Scalable architectures for phenotype librariesScalable architectures for phenotype libraries
Scalable architectures for phenotype libraries
Martin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
Martin Chapman
 
Using AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patientsUsing AI to autonomously identify diseases within groups of patients
Using AI to autonomously identify diseases within groups of patients
Martin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
Martin Chapman
 
Principles of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical softwarePrinciples of Health Informatics: Evaluating medical software
Principles of Health Informatics: Evaluating medical software
Martin Chapman
 
Principles of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical softwarePrinciples of Health Informatics: Usability of medical software
Principles of Health Informatics: Usability of medical software
Martin Chapman
 
Principles of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile healthPrinciples of Health Informatics: Social networks, telehealth, and mobile health
Principles of Health Informatics: Social networks, telehealth, and mobile health
Martin Chapman
 
Principles of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcarePrinciples of Health Informatics: Communication systems in healthcare
Principles of Health Informatics: Communication systems in healthcare
Martin Chapman
 
Principles of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systemsPrinciples of Health Informatics: Terminologies and classification systems
Principles of Health Informatics: Terminologies and classification systems
Martin Chapman
 
Principles of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledgePrinciples of Health Informatics: Representing medical knowledge
Principles of Health Informatics: Representing medical knowledge
Martin Chapman
 
Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...Principles of Health Informatics: Informatics skills - searching and making d...
Principles of Health Informatics: Informatics skills - searching and making d...
Martin Chapman
 
Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...Principles of Health Informatics: Informatics skills - communicating, structu...
Principles of Health Informatics: Informatics skills - communicating, structu...
Martin Chapman
 
Principles of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systemsPrinciples of Health Informatics: Models, information, and information systems
Principles of Health Informatics: Models, information, and information systems
Martin Chapman
 
Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...Using AI to understand how preventative interventions can improve the health ...
Using AI to understand how preventative interventions can improve the health ...
Martin Chapman
 
Ad

Recently uploaded (20)

Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 

An Introduction to Programming in Java: Arrays

  • 1. Modified by Martin Chapman 4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1 Java for Everyone by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Slides by Donald W. Smith TechNeTrain.com Martin Chapman
  • 2. Contents  Arrays  The Enhanced for Loop  Common Array Algorithms  Using Arrays with Methods  Two-Dimensional Arrays  Array Lists
  • 3. Chapter Goals  To become familiar with using arrays and array lists to collect values  To use the enhanced for loop for traversing arrays and array lists  To learn about common algorithms for processing arrays and array lists  To learn how to use two-dimensional arrays In this chapter, you will learn about arrays, array lists, and common algorithms for processing them.
  • 4. 1. Why do we need arrays?
  • 5. Sequences of Values ‣ A Computer Program often needs to store a list of values and then process them. ‣ For example, to find the highest. ‣ Say you had this list of values, how many variables would you need? ‣ double input1, input2, input3…. ‣ Impractical for manipulation; unnecessary code replication.
  • 6. An Example beer Carlsberg, Guinness, Budweiser
  • 7. An Example if ( Carlsberg.alcoholPercentage is >= 5 ) then My head hurts otherwise In for work at 9am end if ( Guinness.alcoholPercentage is >= 5 ) then My head hurts otherwise In for work at 9am end if ( Budweiser.alcoholPercentage is >= 5 ) then ... Only a ‘pseudocode’ example beer Carlsberg, Guinness, Budweiser
  • 8. Arrays ‣ Are the answer! An array collects sequences of values of the same type.
  • 10. Declaring an Array  Declaring an array is a two step process. 1) double[] data; // declare array variable 2) data = new double[10]; // initialise size You cannot use the array until you tell the compiler the size of the array in step 2.
  • 11. Declaring an Array (Step 1)  Make a named ‘list’ with the following parts: Type Square Braces Array name semicolon double [ ] data ;  You are declaring that • There is an array named data • The elements inside are of type double • You have not (YET) declared how many elements are in inside  Other Rules:  Arrays can be declared anywhere you can declare a variable  Do not use ‘reserved’ words or already used names
  • 12. Declaring an Array (Step 2) data [0] [1] [2] [3] [4] … [9] double double double double double double  Reserve memory for all of the elements: Array name Keyword Type Size semicolon data = new double [10] ;  You are reserving memory for: • The array named data • Needs storage for [10] • Elements the size of type double  You are also setting up the array variable  Now the compiler knows how many elements there are
  • 13. Common Error 1 double[] data; ... data[0] = 29.95; // Error—data not initialised  Uninitialised Arrays  Don’t forget to allocate the array contents!  The compiler will catch this error data 0 1 2 3 4 5 6 7 8 9 double[] data; data = new double[10]; data[0] = 29.95; // No error Error: D:JavaUnitialised.java:7: variable data might not have been initialized
  • 14. One Step Array Declaration  Declare and Create at the same time: Type Braces Array name Keyword Type Size semi double [] data = new double [10] ;  You are declaring that • There is an array named data • The elements inside are of type double  You are reserving memory for the array • Needs storage for [10] • Elements the size of type double  You are also setting up the array variable
  • 15. Declaring and Initialising an Array  You can declare and set the initial contents of all elements by: Type Braces Array name contents list semi int [ ] primes = { 2, 3, 5, 7} ;  You are declaring that  There is an array named primes  The elements inside are of type int  Reserve space for four elements • No need for ‘new’ keyword, the compiler counts them for you.  Set initial values to 2, 3, 5, and 7  Note the curly braces around the contents list
  • 17. Accessing Array Elements  Each element is numbered  We call this the ‘index’  Access an element by: • Name of the array • Index number data[i] public static void main(String[] args) { double data[]; data = new double[10]; data[4] = 35; System.out.println(data[4]); } Elements in the array data are accessed by an integer index i, using the notation data[i].
  • 18. The last element is at index 9: Array Index Numbers  Array index numbers start at 0  The rest are positive integers  A 10 element array has indexes 0 through 9  There is NO element 10! public static void main(String[] args) { double data[]; data = new double[10]; } The first element is at index 0:
  • 19. Problem: Common Error 2  Array Bounds Errors  Accessing a nonexistent element is very common error  Array indexing starts at 0  Your program will stop at run time public class OutOfBounds { public static void main(String[] args) { double data[]; data = new double[10]; data[10] = 100; } } java.lang.ArrayIndexOutOfBoundsException: 10 at OutOfBounds.main(OutOfBounds.java:7) The is no element 10:
  • 20. Solution: Array Bounds Checking  An array knows how many elements it can hold  data.length is the size of the array named data  It is an integer value (index of the last element + 1)  Use this to range check and prevent bounds errors public static void main(String[] args) { int i = 10, value = 34; double data[]; data = new double[10]; if (0 <= i && i < data.length) // value is 10 { data[i] = value; } }
  • 21. Visiting Array Elements  An array knows how many elements it can hold  data.length is the size of the array named data  It is an integer value (index of the last element + 1)  Similarly, use this to visit all the elements in an array. public static void main(String[] args) { int[ ] data = { 1 , 2 , 3 , 4 , 5 }; for ( int i = 0; i < data.length; i++ ) { System.out.println( data[ i ] ); } }
  • 22.  The benefits of using an array: Back to Beer... beer array = { Carlsberg, Guinness, Budweiser } Set variable i = 0; Loop until i == length of beer array if element at i alcoholContent is > 5 then My head hurts otherwise In for work at 9am end increase i by 1. Next Loop. A significant decrease in code.
  • 24. Array Syntax Review  To declare an array, specify the:  Array variable name  Element Type  Length (number of elements)
  • 27. Problems? double[] inputs = new double[ ? ]; for (i = 0; i < inputs.length; i++) { inputs[i] = in.nextDouble(); }
  • 28. Problems? double[] inputs = new double[ ? ]; for (i = 0; i < inputs.length; i++) { inputs[i] = in.nextDouble(); } double[] inputs = new double[100]; while (in.hasNextDouble()) { inputs[ ? ] = in.nextDouble(); }
  • 29. Problems? for (int i = 0; i < ? ; i++) { System.out.println(data[i]); }
  • 30. Partially-Filled Arrays  An array cannot change size at run time  The programmer may need to guess at the maximum number of elements required  It is a good idea to use a constant for the size chosen  A partial solution?  Use a variable to track how many elements are filled
  • 31. Partially-Filled Arrays final int LENGTH = 100; double[] data = new double[LENGTH]; int currentSize = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (currentSize < data.length) { data[currentSize] = in.nextDouble(); currentSize++; } } Use the .length value and currentSize variable to prevent over-filling the array
  • 32. ‘Walking’ a Partially Filled Array for (int i = 0; i < currentSize; i++) { System.out.println(data[i]); } A for loop is a natural choice to walk through an array ‣ Use currentSize, not data.length for the last element
  • 33.  Using for loops to ‘walk’ arrays is very common  The enhanced for loop simplifies the process  Also called the “for each” loop  Read this code as: • “For each element in data” double[] data = . . .; double sum = 0; for (double element : data) { sum = sum + element; } A shortcut: The Enhanced for Loop
  • 34.  As the loop proceeds, it will:  Access each element in order (0 to length -1)  Copy it to the element variable  Execute loop body  Not possible to:  Change elements  Get bounds error double[] data = . . .; double sum = 0; for (double element : data) { sum = sum + element; } A shortcut: The Enhanced for Loop
  • 35. Syntax: The “for each” loop  Use the “for each” loop when:  You need to access every element in the array  You do not need to change any elements of the array
  • 36. Common Array Algorithms  Practical array implementations:  Filling an Array  Sum and Average Values  Maximum and Minimum  Output Elements with Separators  Linear Search  Removing an Element  Inserting an Element  Copying Arrays  Reading Input
  • 37. Common Algorithms 1: 1) Filling an Array  Initialise an array to a set of calculated values  Example: Fill an array with squares of 0 through 10 int[] squares = new int[11]; for (int i = 0; i < squares.length; i++) { squares[i] = i * i; }
  • 38. Common Algorithms 2: 2) Sum and Average  Use ‘for each’ loop, and make sure not to divide by zero double total = 0, average = 0; for (double element : data) { total = total + element; } if (data.length > 0) { average = total / data.length; }
  • 39. Common Algorithms 3: double largest = data[0]; for (int i = 1; i < data.length; i++) { if (data[i] > largest) { largest = data[i]; } } double largest = data[0]; for (double element : data) { if (element > largest) largest = element; }  Maximum and Minimum  Set largest to first element  Use for or a ‘for each’ loop  Use the same logic for minimum double smallest = data[0]; for (double element : data) { if (element < smallest) smallest = element; } Typical for loop to find maximum ‘for each’ to find maximum ‘for each’ to find minimum
  • 40.  Element Separators  Output all elements with separators between them  No separator before the first or after the last element  Handy Array method: Arrays.toString()  Useful for debugging! Common Algorithms 4: for (int i = 0; i < data.length; i++) { if (i > 0) { System.out.print(" | "); } System.out.print(data[i]); } import java.util.*; System.out.println(Arrays.toString(data));
  • 41. Common Algorithms 5:  Linear Search  Search for a specific value in an array  Start from the beginning (left), stop if/when it is found  Uses a boolean ‘found’ flag to stop loop if found int searchedValue = 100; int pos = 0; boolean found = false; while (pos < data.length && !found) { if (data[pos] == searchedValue) { found = true; } else { pos++; } if (found) { System.out.println(“Found at position: ” + pos); } else { System.out.println(“Not found”); } } Compound condition to prevent bounds error if value not found.
  • 42. Common Algorithms 6:  Removing an element (at a given position)  Requires tracking the ‘current size’ (# of valid elements)  But don’t leave a ‘hole’ in the array!  Solution depends on if you have to maintain ‘order’ • If not, find the last valid element, copy over position, update size data[pos] = data[currentSize – 1]; currentSize--;
  • 43. Common Algorithms 6:  Removing an element (at a given position)  Requires tracking the ‘current size’ (# of valid elements)  But don’t leave a ‘hole’ in the array!  Solution depends on if you have to maintain ‘order’ • If so, move all of the valid elements after ‘pos’ up one spot, update size for (int i = pos; i < currentSize - 1; i++) { data[i] = data[i + 1]; } currentSize--;
  • 44. Common Algorithms 7:  Inserting an Element  Solution depends on if you have to maintain ‘order’ • If so, find the right spot for the new element, move all of the valid elements after ‘pos’ down one spot, insert the new element, and update size • If not, just add it to the end and update the size if (currentSize < data.length) { for (int i = currentSize; i > pos; i--) { data[i] = data[i - 1]; } data[pos] = newElement; currentSize++; }
  • 45. Note: Array References  Make sure you see the difference between the:  Array variable: The named ‘handle’ to the array  Array contents: Memory where the values are stored int[] scores = { 10, 9, 7, 4, 5 }; An array variable contains a reference to the array contents. The reference is the location of the array contents (in memory). Array variable Array contents Reference Values
  • 46. Note: Array Aliases  You can make one array reference refer to the same contents of another: int[] scores = { 10, 9, 7, 4, 5 }; Int[] values = scores; // Copying the array reference An array variable specifies the location of an array. Copying the reference yields a second reference to the same array. Array contents References
  • 47. Common Algorithms 8:  Copying Arrays  Not the same as copying only the reference • Only have one actual set of contents!
  • 48. Common Algorithms 8: double[] data = new double[6]; . . . // Fill array double[] prices = data; // Only a reference so far double[] prices = Arrays.copyOf(data, data.length); // copyOf creates the new copy, returns a reference  Want to copy the contents of one array to another  Use the Arrays.copyOf method
  • 49. Common Algorithms 8:  Growing an array  Copy the contents of one array to a larger one  Change the reference of the original to the larger one  Example: Double the size of an existing array  Use the Arrays.copyOf method  Use ‘2 *’ in the second parameter double[] values = new double[6]; . . . // Fill array double[] newValues = Arrays.copyOf(values, 2 * values.length); values = newValues; Arrays.copyOf second parameter is the length of the new array
  • 50. Increasing the Size of an Array - Step 1  Copy all elements of values to newValues double[] newValues = Arrays.copyOf(values, 2 * values.length);
  • 51. Increasing the Size of an Array - Step 2  Then copy newValues reference over values reference values = newValues;
  • 52. Common Algorithms 9:  Reading Input  Solution depends on if know how many values to expect • If so, make an array of that size and fill it one-by-one • double[] inputs = new double[NUMBER_OF_INPUTS]; for (i = 0; i < inputs.length; i++) { inputs[i] = in.nextDouble(); }
  • 53. Common Algorithms 9:  Reading Input  Solution depends on if know how many values to expect • If so, make an array of that size and fill it one-by-one • If not, make an array large enough for the maximum, and add values to the end until no more are available. double[] inputs = new double[NUMBER_OF_INPUTS]; for (i = 0; i < inputs.length; i++) { inputs[i] = in.nextDouble(); } double[] inputs = new double[MAX_INPUTS]; int currentSize = 0; while (in.hasNextDouble() && currentSize < inputs.length) { inputs[currentSize] = in.nextDouble(); currentSize++; }
  • 54. Common Algorithms 9: double[] inputs = new double[INITIAL_SIZE]; int currentSize = 0; while (in.hasNextDouble()) { if (currentSize >= inputs.length) { inputs = Arrays.copyOf(inputs, 2 * inputs.length); } inputs[currentSize] = in.nextDouble(); currentSize++; }  Reading Input  A better solution: double the array when it is full.  Able to handle input of arbitrary length
  • 55. LargestInArray.java (1) Input values and store in next available index of the array
  • 56. LargestInArray.java (2) Use a for loop and the ‘Find the largest’ algorithm
  • 57. Common Error 3  Underestimating the Size of the Data Set  The programmer cannot know how someone might want to use a program!  Make sure that you write code that will politely reject excess input if you used fixed size limits Sorry, the number of lines of text is higher than expected, and some could not be processed. Please break your input into smaller size segments (1000 lines maximum) and run the program again.
  • 58. Think you’re ahead? Friday 2pm - 4pm, Lab S4.01 Objects, classes, data structures, GUIs... [email protected]
  • 59. Feel like you’re behind? Friday 2pm - 4pm, Lab S4.01 Cover all basic concepts. [email protected]