introduction to arrays

11
Introduction to Arrays Chapter 10

Upload: byron-santos

Post on 31-Dec-2015

30 views

Category:

Documents


3 download

DESCRIPTION

Chapter 10. Introduction to Arrays. What is an array?. An array is an ordered collection that stores many elements of the same type within one variable name. Elements are the items in an array. Each element is identified with an index number. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to Arrays

Introduction to Arrays

Chapter 10

Page 2: Introduction to Arrays

10

What is an array?An array is an ordered collection that stores many elements of the same type within one variable name.

Elements are the items in an array.

Each element is identified with an index number.

Index numbers always start at 0 for the first element.

Page 3: Introduction to Arrays

10

Declaring ArraysIdentify type of array

Use square bracketsint[] myArray;

Declares an array of int values

Page 4: Introduction to Arrays

10

Instantiating ArraysUse the new keyword

Identify number of elementsmyArray = new int[1000];

Instantiates myArray with 1000 elements

You can declare and instantiate in one line

int[] myArray = new int[1000];

Page 5: Introduction to Arrays

10

Putting Values in the ArrayUse the index operator to assign a value at a particular place in the array.myArray[10] = 100;

Assigns the value 100 to the 10th element in the array

Most programs use a for loop to iterate the array.

Page 6: Introduction to Arrays

10

Initializing the ArrayYou can initialize the array with values at the same time the array is created.int[] myArray = {1, 2, 3, 4, 5};

Page 7: Introduction to Arrays

10Determining the Length of the

ArrayUse the length property to find the number of elements in the array.System.out.println(myArray.length);

Displays the length of the array in the console

For ( int i = 0; i < myArray.length; i++ );

Uses the length property to set up the for loop

Page 8: Introduction to Arrays

10

Passing by ValueIntrinsic types are passed to methods by value.

A copy of the value is passed.

The original value is unchanged.

Page 9: Introduction to Arrays

10

Passing by ReferenceObjects are passed to methods by reference.

The reference points to the original object.

A change to the object affects the object in the calling method.

Page 10: Introduction to Arrays

10

Passing Arrays to MethodsAn array is an object type.

Passed by reference

Elements of arrays are not necessarily passed by reference.

Depends on the underlying element type

Extracting int elements from an array and passing them to a method passes them by value

Page 11: Introduction to Arrays

10Using Polymorphic Objects

in an ArrayAn array can hold objects that:

Derive from the same base class

Implement a common interface