1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and 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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 2 Section 2.2 Console Input Using The Scanner CLASS Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
Chapter 5: ARRAYS ARRAYS. Why Do We Need Arrays? Java Programming: From Problem Analysis to Program Design, 4e 2  We want to write a Java program that.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Arrays. Arrays are objects that help us organize large amounts of information.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Input/Output.
Project 1.
CSC 1051 – Data Structures and Algorithms I
Chapter 6 More Conditionals and Loops
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Arrays in Java.
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

1 Arrays Chapter 8

Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize an array in the declaration. Write a loop to process the items of an array. 2

3 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information. Today we will focuses on: Array declaration and use Bounds checking and capacity Arrays that store object references Pitfall: Scanner class, nextLine method (Not in the textbook)

4 Arrays An array is an ordered list of values scores The entire array has a single name Each entry has a numeric index An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

5 Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; The type of the variable scores is int[] Array of integers The reference variable scores is set to a new array object that can hold 10 integers.

6 Declaring and Using Arrays Some other examples of array declarations: double[] prices = new double[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

7 Array Elements A particular entry in an array is referenced using the array name followed by the index in brackets. For example, the expression scores[2] refers to the 3rd value in the array scores.

8 Array Entries scores[2] The expression represents a place to store a single integer and can be used wherever an integer variable can be used.

9 Array Elements The values held in an array are called array elements. An array stores multiple values of the same type The element type The element type can be a primitive type or an object reference. Therefore, we can create an array of integers, an array of characters, an array of String objects, etc.

10 Array Elements An array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; scores[0] = scores[0] + 2; System.out.println ("Top = " + scores[5]); Anything that we could do with an integer variable.

11 Arrays In Java, the array itself is an object that must be instantiated. Another way to picture the scores array: scores

public class BasicArray { // // Creates an array, fills it with various integer // values,modifies one value, then prints them out. // public static void main (String[] args) { final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) { list[index] = index * MULTIPLE; } list[5] = 999; // change one array value for (int index = 0; index < LIMIT; index++) { System.out.println(list[index]); } 12 BasicArray.java

BasicArray Running 13

14 Exercise Write a program to declare an array named nums of ten elements of type int and initialize the elements (starting with the first) to the values 2, 4, 6, 8,..., 18, 20 respectively. End of Section

15 Array Index and Bounds Checking Once an array is created, it has a fixed size An index used in an array reference must specify a valid element. The index value must be in range 0 to N-1 The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking. Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

16 Bounds Checking If the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99. The following reference will cause an exception to be thrown: for (int index=0; index <= 100; index++) { codes[index] = index*50 + epsilon; } problem Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

BasicArray Example 17 Suppose we made this mistake.

Here is what would happen 18

19 Bounds Checking Each array object has a public constant called length that stores the size of the array. It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index. No parentheses Unlike the String method length()

20 ReverseOrder.java import java.util.Scanner; public class ReverseOrder { public static void main (String[] args) { Scanner scan = new Scanner (System.in); double[] numbers = new double[5]; System.out.println ("The size of the array: " + numbers.length); for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) { System.out.print (numbers[index] + " "); }

ReverseOrder Running 21

22 Exercise Assume that an array of integers named numbers has been declared and initialized. Write a single statement that assigns a new value to the first element of the array. The new value should be equal to twice the value stored in the last element of the array. End of Section

23 Initializer Lists An initializer list can be used to instantiate and fill an array in one step. The values are delimited by braces and separated by commas. Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

24 Initializer Lists Note that when an initializer list is used: The new operator is not used. No size value is specified. The size of the array is determined by the number of items in the initializer list. An initializer list can be used only in the array declaration. Not in assignment statements. End of Section

25 Arrays of Objects The elements of an array can be object references. The following declaration reserves space to store 5 references to String objects String[] words = new String[5];

26 Arrays of Objects String[] words = new String[5]; This does NOT create any String objects. Initially an array of objects holds null references. Each object stored in an array must be instantiated separately. It is a reference to the object, not the object itself, that is stored in the array.

27 Arrays of Objects The words array when initially declared: words At this point, the following reference would throw a NullPointerException : System.out.println (words[0]);

28 Arrays of Objects After some String objects are created and stored in the array: "friendship" words - - "loyalty" "honor"

29 Arrays of Objects Keep in mind that String objects can be created using literals. The following declaration creates an array object called verbs and fills it with four String objects created using string literals. String[] verbs = {"play", "work", "eat", "sleep"}; End of Section

30 Pitfall: Scanner Class, nextLine method Scanner, nextLine method: Reads the remainder of a line of text and returns as a string. Starting whenever the last keyboard reading left off The line terminator '\n' is read and discarded, not included in the string returned. int number = scan.nextInt(); String str1 = scan.nextLine(); String str2 = scan.nextLine();

31 Pitfall: Scanner Class, nextLine method Pitall: calling nextLine after next, nextInt, nextDouble method next, nextInt, or nextDouble reads the input but does not read the new line ('\n') character. The new line character is left in the keyboard input buffer. So the nextLine invocation after reads the rest of the line, which is nothing other than '\n' and returns the empty string.

32 Pitfall: Scanner Class, nextLine method Fix the problem: Include an extra call to nextLine() to clear the New Line character after calling next, nextInt, or nextDouble. int number = scanner.nextInt(); scanner.nextLine(); String str1 = scanner.nextLine(); String str2 = scanner.nextLine();

33 Readings and Assignments Reading: Chapter Self-Assessment Exercises: Self-Review Questions Section SR 8.3, 8.10, 8.11, 8.15 After Chapter Exercises EX 8.1, 8.4, 8.5 a, b, 8.7, 8.8 Project 8 End of Presentation