Based on slides from Deitel & Associates, Inc.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Visual Basic 2010 How to Program
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Lists, Loops, Validation, and More
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Introduction to C Programming
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
1.
Chapter 7: Arrays In this chapter, you will learn about
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 10 Arrays and Tile Mapping Starting Out with Games & Graphics.
Chapter 24 Lists, Stacks, and Queues
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 12 – Security Panel Application Introducing.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Arrays.
CS 141 Computer Programming 1 1 Arrays. Outline  Introduction  Arrays  Declaring Arrays  Examples Using Arrays  Sorting Arrays  Multiple-Subscripted.
Pointers and Arrays Chapter 12
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 13 – Salary Survey Application: Introducing.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Chapter 10 Introduction to Arrays
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
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.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
 Pearson Education, Inc. All rights reserved Arrays.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
CS0007: Introduction to Computer Programming Introduction to Arrays.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
 Pearson Education, Inc. All rights reserved Arrays.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 20 Generic Classes and Methods
Java How to Program, Late Objects Version, 10/e
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.
Object Oriented Programming in java
MSIS 655 Advanced Business Applications Programming
Arrays.
Chapter 7 Arrays and ArrayLists
Presentation transcript:

Based on slides from Deitel & Associates, Inc. Arrays Based on slides from Deitel & Associates, Inc. Revised by T. A. Yang

Outline Arrays Arrays and Loops Arrays as parameters to methods One-dimensional arrays Multi-dimensional arrays Arrays and Loops Arrays as parameters to methods The java.util.Arrays class The java.util.ArrayList class Examples & exercises

7.1 Introduction Data structures Arrays Collections of related data items. Discussed in depth in Chapters 20–22. A separate course: csci 3333 Data Structures Arrays Data structures consisting of related data items of the same type. Make it convenient to process related groups of values. Remain the same length once they are created. Arrays are objects so they are reference types. Elements can be either primitive or reference types.

The class java.util.Arrays: static methods for common array manipulations The ArrayList collection Similar to arrays Dynamic resizing They automatically increase their size at execution time to accommodate additional elements.

int [ ] c; int c[ ]; int c[ ] = {-45, 6, 0, 72, 1543, -89, 0, 62, -3, 1, 6453, 78};

An index must be a nonnegative integer. Can use an expression as an index. Every array object knows its own length and stores it in an instance variable called length. length cannot be changed because it’s a final variable.

7.3 Declaring and Creating Arrays Array objects Created with keyword new. You specify the element type and the number of elements in an array-creation expression, which returns a reference that can be stored in an array variable. Declaration and array-creation expression for an array of 12 int elements int[] c = new int[ 12 ]; Can be performed in two steps as follows: int[] c; // declare the array variable c = new int[ 12 ]; // creates the array

When an array is created, each element of the array receives a default value. Zero for the numeric primitive-type elements, false for boolean elements and null for references.

Array initializer A comma-separated list of expressions (called an initializer list) enclosed in braces. Used to create an array and initialize its elements. Array length is determined by the number of elements in the initializer list. int[] n = { 10, 20, 30, 40, 50 }; Creates a five-element array with index values 0–4. Compiler counts the number of initializers in the list to determine the size of the array It sets up the appropriate new operation “behind the scenes.”

final variables must be initialized before they are used and cannot be modified thereafter. An attempt to modify a final variable after it’s initialized causes a compilation error cannot assign a value to final variable An attempt to access the value of a final variable before it’s initialized causes a compilation error

Many programs present data to users in a graphical manner. Fig. 7.6: BarChart.java Many programs present data to users in a graphical manner. Numeric values are often displayed as bars in a bar chart. A simple way to display numeric data is with a bar chart that shows each numeric value as a bar of asterisks (*). Format specifier %02d indicates that an int value should be formatted as a field of two digits. The 0 flag displays a leading 0 for values with fewer digits than the field width (2).

Fig. 7.7 shows an array version of this application. Sometimes, programs use counter variables to summarize data, such as the results of a survey. Fig. 6.7 used separate counters in a die-rolling program to track the number of occurrences of each side of a six-sided die as the program rolled the die 6,000,000 times. Fig. 7.7 shows an array version of this application. Line 14 of this program replaces lines 23–46 of Fig. 6.7. Array frequency must be large enough to store six counters. We use a seven-element array in which we ignore frequency[0] More logical to have the face value 1 increment frequency[1] than frequency[0].

Bounds checking and exceptions JVM checks array indices to ensure that they are greater than or equal to 0 and less than the length of the array. If the program tries to reference an element that is outside the bounds of the array, Java generates an exception to indicate that an error occurred in the program at execution time. An exception indicates a problem that occurs while a program executes. The name “exception” suggests that the problem occurs infrequently — if the “rule” is that a statement normally executes correctly, then the problem represents the “exception to the rule.” Exception handling enables you to create fault-tolerant programs that can resolve (or handle) exceptions.

Exception handling To handle an exception, place any code that might throw an exception in a try statement. The try block contains the code that might throw an exception. The catch block contains the code that handles the exception if one occurs. You can have many catch blocks to handle different types of exceptions that might be thrown in the corresponding try block.

Executing the catch Block When the program encounters the value 14 in the responses array, it attempts to add 1 to frequency[14], which is outside the bounds of the array — the frequency array has only six elements. Because array bounds checking is performed at execution time, the JVM generates an exception — specifically line 19 throws an ArrayIndexOutOfBoundsException to notify the program of this problem. At this point the try block terminates and the catch block begins executing — if you declared any variables in the try block, they’re now out of scope.

The catch block declares a type and an exception parameter, and can handle exceptions of the specified type. Inside the catch block, you can use the parameter’s identifier to interact with a caught exception object. The exception object’s toString method returns the error message that is stored in the exception object. The exception is considered handled when program control reaches the closing right brace of the catch block. See http://download.oracle.com/javase/6/docs/api/java/lang/ArrayIndexOutOfBoundsException.html

7.6 Enhanced for Statement Iterates through the elements of an array without using a counter. Avoids the possibility of “stepping outside” the array. Also works with the Java API’s prebuilt collections (see Section 7.14). Syntax: for ( parameter : arrayName ) statement where parameter has a type and an identifier and arrayName is the array through which to iterate. Parameter type must be consistent with the array’s element type. The enhanced for statement simplifies the code for iterating through an array.

The enhanced for statement can be used only to obtain array elements It cannot be used to modify elements. To modify elements, use the traditional counter-controlled for statement. Can be used in place of the counter-controlled for statement if you don’t need to access the index of the element.

7.7 Passing Arrays to Methods To pass an array argument to a method, specify the name of the array without any brackets. Since every array object “knows” its own length, we need not pass the array length as an additional argument. To receive an array, the method’s parameter list must specify an array parameter. When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of that reference. When an argument to a method is an individual array element of a primitive type, the called method receives a copy of the element’s value. Such primitive values are called scalars or scalar quantities.

© Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.

Pass-by-value (also called call-by-value) A copy of the argument’s value is passed to the called method. The called method works exclusively with the copy. Changes to the called method’s copy do not affect the original variable’s value in the caller. Pass-by-reference (also called call-by-reference) The called method can access the argument’s value in the caller directly and modify that data, if necessary. Improves performance by eliminating the need to copy possibly large amounts of data.

All arguments in Java are passed by value. A method call can pass two types of values to a method Copies of primitive values Example: (Line 30) modifyElement (array[3]); Copies of references to objects Example: (Line 19) modifyArray (array); If a method modifies a reference-type parameter so that it refers to another object, only the parameter refers to the new object The reference stored in the caller’s variable still refers to the original object. Although an object’s reference is passed by value, a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. The parameter in the called method and the argument in the calling method refer to the same object in memory.

Exercises: int [ ] c1; int c2[ ]; int c3[ ] = {-45, 6, 0, 72, 1543, -89, 0, 62, -3, 1, 6453, 78}; // Exercise 1: display each of the elements in c3; displayArray (c3); // Exercise 2: make c2 the same as c3 c2 = c3; displayArray(c2); // Exercise 3: copy elements in c3 to c1; keep them as separate arrays c1 = Arrays.copyOf (c3, c3.length); displayArray(c1);

Exercises: // Exercise 4: add the values in c2 into c1 // Exercise 5: add the values in c1 to get the sum // Exercise 5: add the values in c1 and c2 and save the sum into the corresponding elements in c3