Top Banner
7 7 Java Arrays Java Arrays Java Fundamentals and Object- Java Fundamentals and Object- Oriented Programming Oriented Programming The Complete Java Boot Camp The Complete Java Boot Camp MELJUN CORTES MELJUN CORTES MELJUN CORTES MELJUN CORTES
23

MELJUN CORTES Java Lecture Arrays

May 13, 2015

Download

Technology

MELJUN CORTES

MELJUN CORTES Java Lecture Arrays
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: MELJUN CORTES Java Lecture Arrays

77 Java ArraysJava Arrays

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Java Lecture Arrays

ObjectivesObjectives

At the end of the lesson, the student should At the end of the lesson, the student should be able to:be able to:

Declare and create arraysDeclare and create arrays Access array elementsAccess array elements Determine the number of elements in an Determine the number of elements in an

arrayarray Declare and create multidimensional arraysDeclare and create multidimensional arrays

Page 3: MELJUN CORTES Java Lecture Arrays

Introduction to ArraysIntroduction to Arrays

Suppose we have here three variables of type int with Suppose we have here three variables of type int with different identifiers for each variable. different identifiers for each variable.

int number1; int number1; int number2; int number2; int number3; int number3;

number1 = 1; number1 = 1; number2 = 2; number2 = 2; number3 = 3; number3 = 3;

As you can see, it seems like a tedious task in order to just As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used initialize and use the variables especially if they are used for the same purpose. for the same purpose.

Page 4: MELJUN CORTES Java Lecture Arrays

Introduction to ArraysIntroduction to Arrays

In Java and other programming languages, In Java and other programming languages, there is one capability wherein we can use there is one capability wherein we can use one variable to store a list of data and one variable to store a list of data and manipulate them more efficiently. This type manipulate them more efficiently. This type of variable is called an array. of variable is called an array.

An array stores multiple data items of the An array stores multiple data items of the same data type, in a contiguous block of same data type, in a contiguous block of memory, divided into a number of slots. memory, divided into a number of slots.

Page 5: MELJUN CORTES Java Lecture Arrays

Declaring ArraysDeclaring Arrays

To declare an array, write the data type, To declare an array, write the data type, followed by a set of square brackets[], followed by a set of square brackets[], followed by the identifier name.followed by the identifier name.

For example, For example, int []ages; int []ages;

or or int ages[];int ages[];

Page 6: MELJUN CORTES Java Lecture Arrays

Array InstantiationArray Instantiation

After declaring, we must create the array and specify After declaring, we must create the array and specify its length with a constructor statement. its length with a constructor statement.

Definitions:Definitions: InstantiationInstantiation

In Java, this means creation

ConstructorConstructor In order to instantiate an object, we need to use a

constructor for this. A constructor is a method that is called to create a certain object.

We will cover more about instantiating objects and constructors later.

Page 7: MELJUN CORTES Java Lecture Arrays

Array InstantiationArray Instantiation

To instantiate (or create) an array, write the To instantiate (or create) an array, write the newnew keyword, followed by the square brackets containing keyword, followed by the square brackets containing the number of elements you want the array to have.the number of elements you want the array to have.

For example,For example,//declaration//declaration int ages[]; int ages[];

//instantiate object//instantiate objectages =ages = new int[100]; new int[100];

or, can also be written as, or, can also be written as, //declare and instantiate object //declare and instantiate object int ages[] = int ages[] = new int[100];new int[100];

Page 8: MELJUN CORTES Java Lecture Arrays

Array InstantiationArray Instantiation

Page 9: MELJUN CORTES Java Lecture Arrays

Array InstantiationArray Instantiation

You can also instantiate an array by You can also instantiate an array by directly initializing it with data.directly initializing it with data.

For example,For example,int arr[] = {1, 2, 3, 4, 5};int arr[] = {1, 2, 3, 4, 5};

This statement declares and instantiates an This statement declares and instantiates an array of integers with five elements array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5).(initialized to the values 1, 2, 3, 4, and 5).

Page 10: MELJUN CORTES Java Lecture Arrays

Sample ProgramSample Program

1 //creates an array of boolean variables with identifier 2 //results. This array contains 4 elements that are 3 //initialized to values {true, false, true, false}

4 boolean results[] = { true, false, true, false };

5 //creates an array of 4 double variables initialized 6 //to the values {100, 90, 80, 75};

7 double []grades = {100, 90, 80, 75};

8 //creates an array of Strings with identifier days and 9 //initialized. This array contains 7 elements

10 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};

Page 11: MELJUN CORTES Java Lecture Arrays

Accessing an Array ElementAccessing an Array Element

To access an array element, or a part of the array, To access an array element, or a part of the array, you use a number called an you use a number called an indexindex or a or a subscriptsubscript. .

index number or subscriptindex number or subscript assigned to each member of the array, to allow the assigned to each member of the array, to allow the

program to access an individual member of the program to access an individual member of the array.array.

begins with zero and progress sequentially by begins with zero and progress sequentially by whole numbers to the end of the array. whole numbers to the end of the array.

NOTE: Elements inside your array are from 0 to NOTE: Elements inside your array are from 0 to (sizeOfArray-1). (sizeOfArray-1).

Page 12: MELJUN CORTES Java Lecture Arrays

Accessing an Array ElementAccessing an Array Element

For example, given the array we declared a For example, given the array we declared a while ago, we have while ago, we have

//assigns 10 to the first element in //assigns 10 to the first element in the array the array

ages[0] = 10; ages[0] = 10;

//prints the last element in the //prints the last element in the array array

System.out.print(ages[99]); System.out.print(ages[99]);

Page 13: MELJUN CORTES Java Lecture Arrays

Accessing an Array ElementAccessing an Array Element

NOTE:NOTE: once an array is declared and constructed, the once an array is declared and constructed, the

stored value of each member of the array will stored value of each member of the array will be initialized to zero for number data.be initialized to zero for number data.

for reference data types such as Strings, they for reference data types such as Strings, they are NOT initialized to blanks or an empty string are NOT initialized to blanks or an empty string “”. Therefore, you must populate the String “”. Therefore, you must populate the String arrays explicitly. arrays explicitly.

Page 14: MELJUN CORTES Java Lecture Arrays

Accessing an Array ElementAccessing an Array Element

The following is a sample code on how to The following is a sample code on how to print all the elements in the array. This print all the elements in the array. This uses a for loop, so our code is shorter.uses a for loop, so our code is shorter.

1 public class ArraySample{ 2 public static void main( String[] args ){ 3 int[] ages = new int[100]; 4 for( int i=0; i<100; i++ ){ 5 System.out.print( ages[i] ); 6 } 7 } 8 }

Page 15: MELJUN CORTES Java Lecture Arrays

Coding GuidelinesCoding Guidelines

1. It is usually better to initialize or instantiate 1. It is usually better to initialize or instantiate the array right away after you declare it. For the array right away after you declare it. For example, the declaration,example, the declaration,

int []arr = new int[100]; int []arr = new int[100];

is preferred over, is preferred over,

int []arr; int []arr; arr = new int[100]; arr = new int[100];

Page 16: MELJUN CORTES Java Lecture Arrays

Coding GuidelinesCoding Guidelines

2. The elements of an n-element array 2. The elements of an n-element array have indexes from 0 to n-1. Note have indexes from 0 to n-1. Note that there is no array element that there is no array element arr[n]! This will result in an array-arr[n]! This will result in an array-index-out-of-bounds exception. index-out-of-bounds exception.

3. Remember: You cannot resize an 3. Remember: You cannot resize an array.array.

Page 17: MELJUN CORTES Java Lecture Arrays

Array LengthArray Length

In order to get the number of elements in In order to get the number of elements in an array, you can use the length field of an an array, you can use the length field of an array. array.

The length field of an array returns the size The length field of an array returns the size of the array. It can be used by writing, of the array. It can be used by writing,

arrayName.length arrayName.length

Page 18: MELJUN CORTES Java Lecture Arrays

Array LengthArray Length

1 public class ArraySample { 2 public static void main( String[] args ){ 3 int[] ages = new int[100];

4 for( int i=0; i<ages.length; i++ ){ 5 System.out.print( ages[i] ); 6 } 7 } 8 }

Page 19: MELJUN CORTES Java Lecture Arrays

Coding GuidelinesCoding Guidelines

1. When creating for loops to process the elements of an 1. When creating for loops to process the elements of an array, use the array object's length field in the condition array, use the array object's length field in the condition statement of the for loop. This will allow the loop to statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays. adjust automatically for different-sized arrays.

2. Declare the sizes of arrays in a Java program using 2. Declare the sizes of arrays in a Java program using named constants to make them easy to change. For named constants to make them easy to change. For example, example,

final int ARRAY_SIZE = 1000; //declare a final int ARRAY_SIZE = 1000; //declare a constant constant . . . . . . int[] ages = new int[ARRAY_SIZE]; int[] ages = new int[ARRAY_SIZE];

Page 20: MELJUN CORTES Java Lecture Arrays

Multidimensional ArraysMultidimensional Arrays

Multidimensional arrays are implemented Multidimensional arrays are implemented as arrays of arrays. as arrays of arrays.

Multidimensional arrays are declared by Multidimensional arrays are declared by appending the appropriate number of appending the appropriate number of bracket pairs after the array name. bracket pairs after the array name.

Page 21: MELJUN CORTES Java Lecture Arrays

Multidimensional ArraysMultidimensional Arrays

For example,For example,

// integer array 512 x 128 elements int[][] twoD = new int[512][128];

// character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24];

// String array 4 rows x 2 columns String[][] dogs = {{ "terry", "brown" },

{ "Kristin", "white" }, { "toby", "gray"}, { "fido", "black"} };

Page 22: MELJUN CORTES Java Lecture Arrays

Multidimensional ArraysMultidimensional Arrays

To access an element in a multidimensional array is To access an element in a multidimensional array is just the same as accessing the elements in a one just the same as accessing the elements in a one dimensional array.dimensional array.

For example, to access the first element in the first For example, to access the first element in the first row of the array dogs, we write, row of the array dogs, we write,

System.out.print( dogs[0][0] );System.out.print( dogs[0][0] );

This will print the String "terry" on the screen. This will print the String "terry" on the screen.

Page 23: MELJUN CORTES Java Lecture Arrays

SummarySummary

ArraysArrays DefinitionDefinition DeclarationDeclaration Instantiation and constructors (brief overview – Instantiation and constructors (brief overview –

to be discussed more later)to be discussed more later) Accessing an elementAccessing an element The length fieldThe length field Multidimensional ArraysMultidimensional Arrays