Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.

Slides:



Advertisements
Similar presentations
Arrays I Savitch Chapter 6.1: Introduction to Arrays.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Arrays Chapter 6 Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Catie Welsh March 28,  Lab 7 due Friday, April 1st, 1pm 2.
Chapter 8: Arrays.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
CSE 1201 Object Oriented Programming ArrayList 1.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
© Rick Mercer Chapter 7 The Java Array Object.  Some variables store precisely one value: a double stores one floating-point number a double stores one.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chapter 7.
Chapter VII: Arrays.
Arrays in Classes and Methods
Arrays 2/4 By Pius Nyaanga.
Chapter 7 Part 1 Edited by JJ Shepherd
EKT472: Object Oriented Programming
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Java How to Program, Late Objects Version, 10/e
Object Oriented Programming in java
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Announcements Lab 6 was due today Lab 7 assigned this Friday
Classes, Objects and Methods
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

Arrays Chapter 6

Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that return an array learn the proper use of an array as an instance variable learn about multidimensional arrays

Objectives, cont. (optional) learn about text fields and text areas in applets (optional) learn to draw arbitrary polygons and polylines in applets

Outline Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays (optional) Graphics Supplement

Introduction to Arrays An array is an object used to store a (possibly large) collection of data. All the data stored in the array must be of the same type. An array object has a small number of predefined methods.

Introduction to Arrays, cont. Sometimes you want to know several things about a collection of data: –the average –the number of items below the average –the number of items above the average –etc. This requires all the items to be stored as variables of one kind or another.

Introduction to Arrays, cont. Arrays satisfy this need. Even though an array is an object in Java, it can be convenient to think of it as a collection of variables of the same type.

Array Basics: Outline Creating and Accessing Arrays Array Details The length Instance Variable Initializing Arrays

Creating and Accessing Arrays example double[] temperature = new double[7]; is like declaring seven variables of type double, named temperature[0], temperature[1], temperature[2], temperature[3], temperature[4], temperature[5], temperature[6].

Creating and Accessing Arrays, cont. These variables can be used just like any other variables of type double. examples temperature[3] = 32.0; temperature[6] = temperature[3] + 5; System.out.println(temperature[6]); temperature[index+1] = 66.5; These variables are called indexed variables, elements, or subscripted variables.

Creating and Accessing Arrays, cont. The integer expression within the square brackets is called the index (or subscript).

Creating and Accessing Arrays, cont. class ArrayOfTemperatures

Creating and Accessing Arrays, cont.

Array Details syntax for creating an array Base_Type[] Array_Name = new Base_Type[Length]; example int[] pressure = new int[100]; or int[] pressure; pressure = new int[100];

Array Details, cont. The type of the elements is called the base type. The base type of an array can be any type including a class type. –for example, Species[] entry = new Species[3]; The number of elements is the length or size of the array.

Brackets [] Brackets [] serve three purposes: –creating the type name example: int[] pressure; –creating the new array pressure = new int[100]; –naming an indexed variable of the array pressure[3] = keyboard.nextInt();

Array Terminology

Singular Array Names Whether an array holds singular primitive types or singular class types, singular names make the code more self-documenting. –for example, entry[2] makes more sense than entries[2].

The length Instance Variable An array has only one public instance variable, namely length. The length variable stores the number of elements the array can hold. Using Array_Name.length typically produces clearer code than using an integer literal.

The length Instance Variable, cont class ArrayOfTemperatures2

Indices and length The indices of an array start with 0 and end with Array_Name.length-1. When a for loop is used to step through an array, the loop control variable should start at 0 and end at length-1. example for (lcv = 0; lcv < temperature.length; index++)

Array Index Out of Bounds Every index must evaluate to an integer which is not less than 0 and not greater than Array_Name.length-1. Otherwise, the index is said to be out of bounds or invalid. An out-of-bounds index will produce a run- time error.

Incomplete Array Processing Loops fail to process an entire array correctly when they –begin with an index other than 0 –end with an index other than length-1. Examples for (i = 1; i < oops.length-1; index++) for (i = 1; i <= oops.length; index++) for (i = 0; i <= oops.length; index++) for (i = 0; i < oops.length-1; index++)

Initializing Arrays An array can be initialized at the time it is declared. example double[] reading = {3,3, 15.8, 9.7]; –The size of the array is determined by the number of values in the initializer list.

Initializing Arrays, cont. Uninitialized array elements are set to the default value of the base type. However, it’s better to use either an initializer list or a for loop. int[] count = new int[100]; for (int i = 0, i < count.length, i++) a[i] = 0;

Arrays in Classes and Methods Arrays can be used as instance variables in classes. Both an indexed variable of an array and an entire array can be a argument of a method. Methods can return an indexed variable of an array or an entire array.

Case Study: Using an Array as an Instance Variable Prepare a sales report showing –which sales associate (or associates) has the highest sales –how each associate’s sales compare to the average. needed for each associate –name –sales figures

Case Study: Using an Array as an Instance Variable, cont. tasks –obtain the data ( getFigures ) –update the instance variables ( update ) –display the results (displayResults)

Case Study: Using an Array as an Instance Variable, cont. class SalesAssociate

Case Study: Using an Array as an Instance Variable, cont. The program uses an array to keep track of the data for all sales associates.

Case Study: Using an Array as an Instance Variable, cont. class SalesReporter

Case Study: Using an Array as an Instance Variable, cont. class SalesReporter, contd.

Case Study: Using an Array as an Instance Variable, cont.

Indexed Variables as Method Arguments An indexed variable can be used anywhere that any other variable of the base type of the array can be used. Hence, an indexed variable can be an argument to a method.

Indexed Variables as Method Arguments, cont. class ArgumentDemo

Indexed Variables as Method Arguments, cont. –Note that the results would be the same if the arguments provided to method average were interchanged.

Indexed Variables as Method Arguments, cont.

Array Subtleties If the base type of an array is a primitive type, then a method to which an array element is passed creates a copy of the array element, and cannot change the original array element. If the base type of an array is a class type, then a method to which an array element is passed creates an alias, and the referenced object can be changed.

Entire Arrays as Method Arguments An entire array can be used as a single argument passed to a method. example double[] a = new double[10]; SampleClass.change(a);... public static void change(double[] d) –No brackets accompany the argument. –Method change accepts an array of any size.

Arguments for the Method main Recall the heading for method main : public static void main(String[] args) Method main takes an array of String values as its argument. A default array of String values is when you run a program.

Arguments for the Method main, cont. Alternatively, an array of String values can be provided in the command line. example java TestProgram Mary Lou –args[0] is set to “Mary” –args[1] is set to “Lou” System.out.println(“Hello “ + args[0] + “ “ + args[1]); prints Hello Mary Lou.

Use of = and == with Arrays The assignment operator = and the equality operator ==, when used with arrays, behave the same as when used with other objects. –The assignment operator creates an alias, not a copy of the array. –The equality operator determines if two references contain the same memory address, not if two arrays contain the same values.

Making a Copy of an Array example int[] a = new int[50]; int[] b = new int[50];... for (int j = 0; j < a.length; j++) b[j] = a[j];

Determining the “Equality” of Two Arrays To determine if two arrays at different memory locations contain the same elements in the same order, define an equals method which determines if –both arrays have the same number of elements –each element in the first array is the same as the corresponding element in the second array.

Determining the “Equality” of Two Arrays, cont. A while loop can be used. –A boolean variable match is set to true. –Each element in the first array is compared to the corresponding element in the second array. –If two elements are different, match is set to false and the while loop is exited. –Otherwise, the loop terminates with match still set to true.

Determining the “Equality” of Two Arrays, cont. class TestEquals

Determining the “Equality” of Two Arrays, cont.

Methods that Return Arrays A method can return an array. The mechanism is basically the same as for any other returned type. example public static Base_Type[] Method_Name (Parameter_List) Base_Type Array_Name; … return Array_Name; The method need not be public or static.

Methods that Return Arrays, cont. class ReturnArrayDemo

Programming with Arrays and Classes: Outline Programming Example Partially Filled Arrays Searching an Array

Programming Example: A Specialized List Class An array can be an instance variable of a class that is accessible only through the class methods. We will define a class whose objects store lists of items, such as a grocery list or a list of things to do. We’ll name the class OneWayNoRepeatsList.

some features of the class –a method for adding an item to the list unless it is on the list already –an array of strings to hold the items –numbering starting with 1 rather than 0 Programming Example: A Specialized List Class, cont.

–a maximum list size –accessor and mutator methods, but no methods for changing or deleting items –a method to erase the entire list

Using Class OneWayNowRepeatsList Let’s discover how OneWayNoRepeatsList works before considering the definition of the class.

Using Class OneWayNowRepeatsList, cont. class ListDemo

Using Class OneWayNowRepeatsList, cont.

More Features of the Class We need a means of determining that the end of the list has been reached. –Let toDoList.getEntryAt(position) return the value null.

More Features of the Class, cont. class OneWayNoRepeatsList

More Features of the Class, cont. class OneWayNoRepeatsList, contd.

More Features of the Class, cont. three ways to detect the end of a list –when the array is at capacity –when position is at the last entry –when position advances beyond the last entry and null is returned

Partially Filled Arrays Sometimes you need some, but not all of the indexed variables in an array. In such situations, it is important to keep track of how much of the array has been used and/or the index of the last entry so that only meaningful values are accessed.

Partially Filled Arrays, cont.

Searching an Array Method onList in class OneWayNoRepeatsList searches the array entry to see if parameter item is in the array entry. This is an example of a sequential search of an array. –The array elements are examined from first to last to see in an item is in the array already.

Returning an Array Instance Variable If a array reference variable can be copied, the elements of the array can be accessed, perhaps improperly, and changed using the alias, even if the array has a private designation. Even when a copy of the array is provided, if its base type is not a primitive type or type String, its elements can be changed unless they, too, are copied.