Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.

Slides:



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

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Chapter 10.
Introduction to arrays Data in economy size packages.
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.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 l Exam.
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
C Programming Lecture 14 Arrays. What is an Array? b An array is a sequence of data items that are: all of the same typeall of the same type –a sequence.
Java Unit 9: Arrays Declaring and Processing Arrays.
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.
HST 952 Computing for Biomedical Scientists Lecture 5.
Classes, Objects, and Methods
Introduction To Scientific Programming Chapter 6 – Arrays.
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.
Lecturer: Dr. AJ Bieszczad Chapter 6 COMP 150: Introduction to Object-Oriented Programming 6-1 l Array Basics l Arrays in Classes and Methods l Programming.
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.
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.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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,
Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
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.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
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];
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Arrays Chapter 7.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
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
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Dr. Sampath Jayarathna Cal Poly Pomona
Presentation transcript:

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Overview l An array: a single name for a collection of data values, all of the same data type »subscript notation identifies precisely one of the values l Arrays are a carryover from earlier programming languages l Array: more than a primitive type, less than an object »their methods are invoked with a special subscript notation –most programmers do not even think of them as methods »they work like objects when used as method arguments and return types »they do not have or use inheritance »they are sort of like a Java class that is not fully implemented Arrays are a natural fit for loops, especially for loops

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Creating Arrays l General syntax for declaring an array: Base_Type[] Array_Name = new Base_Type[Length]; Examples: 80-element array with base type char : char[] symbol = new char[80]; 100-element array of double s: double[] reading = new double[100]; 80-element array of Species : Species[] specimen = new Species[100];

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Programming Tip : Use Singular Array Names l Using singular rather than plural names for arrays improves readability l Although the array contains many elements the most common use of the name will be with a subscript, which references a single value.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Three Ways to Use [ ] (Brackets) with an Array Name 1. To create a type name, e.g. int[] pressure; creates a name with the type " int array" »note that the types int and int array are different »it is the type of the name, not the type of the data 2. To create a new array, e.g. pressure = new int[100]; 3. To name a specific element in the array - also called an indexed variable, e.g. pressure[3] = SavitchIn.readLineInt(); System.out.println("You entered" + pressure[3]);

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Some Array Terminology temperature[n + 2] temperature[n + 2] = 32; Array name Index - also called a subscript - must be an int, - or an expression that evaluates to an int Indexed variable - also called an element or subscripted variable Note that "element" may refer to either a single indexed variable in the array or the value of a single indexed variable. Value of the indexed variable - also called an element of the array

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Array Length Length of an array is specified by the number in brackets when it is created with new »it determines the amount of memory allocated for the array elements (values) »it determines the maximum number of elements the array can hold –storage is allocated whether or not the elements are assigned values The array length can be read with the instance variable length, e.g. the following code displays the number 20 (the size, or length of the Species array, entry ): Species[] entry = new Species[20]; System.out.println(entry.length); The length attribute is established in the declaration and cannot be changed unless the array is redeclared

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Subscript Range l Array subscripts use zero-numbering »the first element has subscript 0 »the second element has subscript 1 »etc. - the n th element has subscript n-1 »the last element has subscript length-1 l For example: int[] scores = {97, 86, 92, 71};

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Subscript out of Range Error Using a subscript larger than length-1 causes a run time (not a compiler) error »an ArrayOutOfBoundsException is thrown –you do not need to catch it or declare it in a throws- clause –you need to fix the problem and recompile your code l Other programming languages, e.g. C and C++, do not even cause a run time error! »one of the most dangerous characteristics of these languages is that they allow out of bounds array indexes.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Initializing an Array's Values in Its Declaration l Array elements can be initialized in the declaration statement by putting a comma-separated list in braces Uninitialized elements will be assigned some default value, e.g. 0 for int arrays l The length of an array is automatically determined when the values are explicitly initialized in the declaration l For example: double[] reading = {5.1, 3.02, 9.65}; System.out.println(readings.length); - displays 3, the length of the array readings

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Initializing Array Elements in a Loop l Array processing is easily done in a loop A for loop is commonly used to initialize array elements l For example: int i;//loop counter/array index int[] a = new int[10]; for(i = 0; i < a.length; i++) a[i] = 0; »note that the loop counter/array index goes from 0 to length - 1 »it counts through length = 10 iterations/elements using the zero-numbering of the array index Programming Tip : Do not count on default initial values for array elements »explicitly initialize elements in the declaration or in a loop

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Arrays and Array Elements as Method Arguments Arrays and array elements can be used with methods just like other objects l both an indexed element and an array name can be an argument in a method l methods can return an array value or an array name

Indexed Variables as Method Arguments nextScore is an array of int s an element of nextScore is an argument of method average average method definition Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Excerpt from ArgumentDemo program in text.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 14 When Can a Method Change an Indexed Variable Argument? Remember: l primitive types are call-by-value »only a copy of the value is passed as an argument in a method call »so the method cannot change the value of the indexed variable l Pass by reference: the address of the object gets passed when it is an argument in a method call »the corresponding argument in the method definition becomes another name for the object »the method has access to the actual object »so the method can change the value of the indexed variable if it is a class (and not a primitive) type

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Array Names as Method Arguments When using an entire array as an argument to a method: l use just the array name and no brackets l as described in the previous slide, the method has access to the original array and can change the value of the elements l the length of the array passed can be different for each call »when you define the function you do not know the length of the array that will be passed »so use the length attribute inside the method to avoid ArrayIndexOutOfBoundsException s

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Example: An Array as an Argument in a Method Call public static void showArray(char[] a) { int i; for(i = 0; i < a.length; i++) System.out.println(a[i]); } the method's argument is the name of an array of characters uses the length attribute to control the loop allows different size arrays and avoids index-out-of- bounds exceptions

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Arguments for the Method main The heading for the main method shows a parameter that is an array of String s: public static void main(String[] args) l When you run a program from the command line, all words after the class name will be passed to the main method in the args array. java TestProgram Josephine Student The following main method in the class TestProgram will print out the first two arguments it receives: l In this example, the output from the command line above will be: Hello Josephine Student Public static void main(String[] args) { System.out.println(“Hello “ + args[0] + “ “ + args[1]); }

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Using = with Array Names: Remember They Are Reference Types int[] a = new int[3]; int[] b = new int[3]; for(int i; i < a.length; i++) a[i] = i; b = a; System.out.println(a[2] + " " + b[2]); a[2] = 10; System.out.println(a[2] + " " + b[2]); The output for this code will be: 2 10 This does not create a copy of array a ; it makes b another name for array a. A value changed in a is the same value obtained with b

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Using == with array names: remember they are reference types int i; int[] a = new int[3]; int[] b = new int[3]; for(i; i < a.length; i++) a[i] = i; for(i; i < b.length; i++) b[i] = i; if(b == a) System.out.println("a equals b"); else System.out.println("a does not equal b"); a and b are both 3-element arrays of int s all elements of a and b are assigned the value 0 tests if the addresses of a and b are equal, not if the array values are equal The output for this code will be " a does not equal b " because the addresses of the arrays are not equal.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Testing Two Arrays for Equality To test two arrays for equality you need to define an equals method that returns true if and only the arrays have the same length and all corresponding values are equal This code shows an example of an equals method.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Methods that Return an Array l Yet another example of passing a reference l Actually, the array is not passed, the address of the array is passed l The local array name within the method is just another name for the original array l The code at right shows an example of returning an array c, newArray, and the return type of vowels are all the same type: char []

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Partially Filled Arrays l Sometimes only part of an array has been filled with data l Array elements always contain something, whether you have written to them or not »elements which have not been written to contain unknown (garbage) data so you should avoid reading them l There is no automatic mechanism to detect how many elements have been filled - you, the programmer need to keep track! An example: the instance variable countOfEntries (in the class OneWayNoRepeatsList ) is incremented every time addItem is called (see the text)

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Example of a Partially Filled Array entry[0]Buy milk. entry[1]Call home. entry[2]Go to beach. entry[3] entry[4] countOfEntries - 1 garbage values countOfEntries has a value of 3. entry.length has a value of 5.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Summary Part 1 l An array may be thought of as a collection of variables, all of the same type. l An array is also may be thought of as a single object with a large composite value of all the elements of the array. Arrays are objects created with new in a manner similar to objects discussed previously.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 25 Summary Part 2 l Array indexes use zero-numbering: »they start at 0, so index i refers to the (i+1)th element; »the index of the last element is (length-of-the-array - 1). »Any index value outside the valid range of 0 to length-1 will cause an array index out of bounds error when the program runs. l A method may return an array. l A "partially filled array" is one in which values are stored in an initial segment of the array: »use an int variable to keep track of how many variables are stored.