Arrays (Java Tutorial)

  • Upload
    amihan

  • View
    234

  • Download
    0

Embed Size (px)

Citation preview

  • 8/20/2019 Arrays (Java Tutorial)

    1/29

    1

     

    Java ArrayJava Array

  • 8/20/2019 Arrays (Java Tutorial)

    2/29

    2

    Agenda

    ● What is an array

    ● Declaration of an array

    ● Instantiation of an array

    ●  Accessing array element

    ●  Array length

    ● Multi-dimensional array

  • 8/20/2019 Arrays (Java Tutorial)

    3/29

    3

     

    What is an Array?What is an Array?

  • 8/20/2019 Arrays (Java Tutorial)

    4/29

    4

    Introduction to Arrays

    ● Suppose we have here three variables of type int withdifferent identifiers for each variable.

    int number1;

    int number2;int number3;

    number1 = 1;

    number2 = 2;number3 = 3;

     As you can see, it seems lie a tedious tas in order to !ustinitiali"e and use the variables especially if they are used forthe same purpose.

  • 8/20/2019 Arrays (Java Tutorial)

    5/29

    5

    Introduction to Arrays

    ● In #ava and other programming languages, there is onecapability wherein we can use one variable to store a list ofdata and manipulate them more efficiently. $his type ofvariable is called an array.

    ●  An array stores multiple data items of the same data type, ina contiguous bloc of memory, divided into a number ofslots.

  • 8/20/2019 Arrays (Java Tutorial)

    6/296

     

    Declaration of Declaration of an Arrayan Array

  • 8/20/2019 Arrays (Java Tutorial)

    7/29

    7

    Declaring Arrays

    ● $o declare an array, write the data type, followed by a set ofs%uare bracets&', followed by the identifier name.

    (or e)ample,int []ages;or

    int ages[];

  • 8/20/2019 Arrays (Java Tutorial)

    8/29

    8

     

    Instantiation ofInstantiation ofan Arrayan Array

  • 8/20/2019 Arrays (Java Tutorial)

    9/29

    9

    Array Instantiation

    ●  After declaring, we must create the array and specify itslength with a constructor statement.

    ● Definitions*

     – Instantiation

    ● In #ava, this means creation

     – +onstructor 

    In order to instantiate an ob!ect, we need to use a constructor for this. Aconstructor is a method that is called to create a certain ob!ect.

    ● We will cover more about instantiating ob!ects and constructors later.

  • 8/20/2019 Arrays (Java Tutorial)

    10/29

    10

    Array Instantiation

    ● $o instantiate or create an array, write the new eyword,followed by the s%uare bracets containing the number ofelements you want the array to have.

    ● (or e)ample,//declaration

     int ages[];

    //instantiate objectages = new int[100];

    or, can also be written as,//declare and instantiate object

    int ages[] = new int[100];

  • 8/20/2019 Arrays (Java Tutorial)

    11/29

    11

    Array Instantiation

  • 8/20/2019 Arrays (Java Tutorial)

    12/29

    12

    Array Instantiation

    ● ou can also instantiate an array by directly initiali"ing it withdata.

    ● (or e)ample,int arr[] = {1, 2, 3, 4, 5};

    $his statement declares and instantiates an array of integerswith five elements initiali"ed to the values /, 0, 1, 2, and 3.

  • 8/20/2019 Arrays (Java Tutorial)

    13/29

    13

    Sample Program1 //creates an array of boolean variables with identifier2 //results. This array contains 4 elements that are3 //initialized to values {true, false, true, false}45 boolean results[] = { true, false, true, false }; 67 //creates an array of 4 double variables initialized

    8 //to the values {100, 90, 80, 75};910 double []grades = {100, 90, 80, 75};1112 //creates an array of Strings with identifier days and13 //initialized. This array contains 7 elements14

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

  • 8/20/2019 Arrays (Java Tutorial)

    14/29

    14

     

    Accessing ArrayAccessing ArrayElement Element 

  • 8/20/2019 Arrays (Java Tutorial)

    15/29

    15

    Accessing an Array Element

    ● $o access an array element, or a part of the array, you usea number called an inde) or a subscript.

    ● inde) number or subscript

     – assigned to each member of the array, to allow the program toaccess an individual member of the array.

     – begins with "ero and progress se%uentially by whole numbers to theend of the array.

     –

    45$6* 6lements inside your array are from 7 to si"e5fArray-/.

  • 8/20/2019 Arrays (Java Tutorial)

    16/29

    16

    Accessing an Array Element

    ● (or e)ample, given the array we declared a while ago, wehave

    //assigns 10 to the first element in the arrayages[0] = 10;

    //prints the last element in the arraySystem.out.print(ages[99]);

  • 8/20/2019 Arrays (Java Tutorial)

    17/29

    17

    Accessing an Array Element

    ● 45$6*

     – once an array is declared and constructed, the stored value of eachmember of the array will be initiali"ed to "ero for number data.

     – for reference data types such as Strings, they are 45$ initiali"ed to

    blans or an empty string 89. $herefore, you must populate the Stringarrays e)plicitly.

  • 8/20/2019 Arrays (Java Tutorial)

    18/29

    18

    Accessing an Array Element

    ● $he following is a sample code on how to print all theelements in the array. $his uses a for loop, so our code isshorter.

    1 public class ArraySample{

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

    4 for( int i=0; i

  • 8/20/2019 Arrays (Java Tutorial)

    19/29

    19

    Coding Guidelines

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

    int []arr = new int[100];

    is preferred over,

    int []arr;

    arr = new int[100];

  • 8/20/2019 Arrays (Java Tutorial)

    20/29

    20

    Coding Guidelines

    2. The elements of an nelement array have indexesfrom ! to n1. "ote that there is no array elementarr#n$% This will result in an arrayindexoutofbounds exception.

    &. 'emember( )ou cannot resize an array.

  • 8/20/2019 Arrays (Java Tutorial)

    21/29

    21

     

    Array LengthArray Length

  • 8/20/2019 Arrays (Java Tutorial)

    22/29

    22

    Array Length

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

    ● $he length field of an array returns the si"e of the array. Itcan be used by writing,

    arrayName.length

  • 8/20/2019 Arrays (Java Tutorial)

    23/29

    23

    Array Length1 public class ArraySample {2 public static void main( String[] args ){3 int[] ages = new int[100];45 for( int i=0; i

  • 8/20/2019 Arrays (Java Tutorial)

    24/29

    24

    Coding Guidelines

    /. When creating for loops to process the elements of anarray, use the array ob!ect:s length field in the conditionstatement of the for loop. $his will allow the loop to ad!ustautomatically for different-si"ed arrays.

    0. Declare the si"es of arrays in a #ava program using namedconstants to mae them easy to change. (or e)ample,

    final int ARRAY_SIZE = 1000; //declare a constant

    . . .int[] ages = new int[ARRAY_SIZE];

  • 8/20/2019 Arrays (Java Tutorial)

    25/29

    25

     

    Multi-DimensionalMulti-DimensionalArrayArray

  • 8/20/2019 Arrays (Java Tutorial)

    26/29

    26

    Multidimensional Arrays

    ● Multidimensional arrays are implemented as arrays ofarrays.

    ● Multidimensional arrays are declared by appending the

    appropriate number of bracet pairs after the array name.

  • 8/20/2019 Arrays (Java Tutorial)

    27/29

    27

    Multidimensional Arrays

    ● (or e)ample,

    // integer array 512 x 128 elements

    int[][] twoD = new int[512][128];

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

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

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

  • 8/20/2019 Arrays (Java Tutorial)

    28/29

    28

    Multidimensional Arrays

    ● $o access an element in a multidimensional array is !ust thesame as accessing the elements in a one dimensional array.

    ● (or e)ample, to access the first element in the first row of

    the array dogs, we write,

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

    $his will print the String ;terry; on the screen.

  • 8/20/2019 Arrays (Java Tutorial)

    29/29

    29

    Summary

    ●  Arrays

     – Definition

     – Declaration

     –

    Instantiation and constructors brief overview < to be discussedmore later

     –  Accessing an element

     – $he length field

     – Multidimensional Arrays