Course Content‎ > ‎Session 3‎ > ‎

Arrays

Introduction

Just like other languages, arrays in Java are used to store a collection of items of the same type into a single unit. More precisely, it can be said that an array is a group of related data items that share a common name. For example, we define an array Salary to represent a set of salaries of a group of employees. An employee salary is indicated by a number called as index number or subscript in brackets after the array name. Salary[10] represents the salary of the 10th employee.

The complete set of values is referred to as an array whereas individual values are referred to as elements. Array can be of any variable type. Array gives the ability to give a single name to represent a collection of items and to refer to an item by using index number. Arrays help in developing short and concise programs. Just imagine how difficult it is, to declare 100 integer variables to represent salary of 100 employees. Given below are the examples of arrays in Java - \

    int Numbers[ ];
    char[ ] letters;
    long grid[ ][ ];  

Declaring an Array

This is the first step in creating an array.  In this step an array variable is created that will hold the array elements. Array variable is declared just like any other variable except that empty brackets i.e. [ ] are used while declaring an array.  Some of the array variable declarations are given below:

    int Score[ ];
    float Temp[ ];
    String Name[ ];

Creating the Array Objects

Unlike other languages, Java does not allow you to specify a number between the empty square brackets to represent number of items in the array. This means when you are declaring an array, Java does not allow you to specify the size of an empty array. The size of the array is specified explicitly:

    char alphabet[ ] = new char[26]; 

Here an array alphabet is declared and it will contain 26 elements of type char.

Here num1 is an integer array declared as

    num1 = new int[3];

num1 is created and it will contain 3 elements When you create an array object using new operator, all the slots of the array are initialized i.e. 0 for numeric arrays, false for boolean, '\0' for character arrays and null for objects.  

Or

    int num[ ] = { 2, 34, 29, 10 };
    String[ ] Names = { "Robert", "Rhea", "Ronnie", "John" };

All the elements inside the braces must be of same type as the variable that holds the array.  In this type of declaration, an array of the size of number of elements included will be automatically created.

Accessing the Array Elements

To access an initial value stored in an array or to assign a new value to an array element, the index number or the subscript of that array element has to be used:

    ArrayName[subscript];

ArrayName is a variable holding an array object subscript. Array subscript starts with 0 (in C and C++ also it starts with 0). For example,

    String[ ] Name = new String[100];

means Name is an array that has 100 slots for storing 100 strings. These strings can be accessed using the subscript from 0 to 99. To assign names to the array, the statements will be:

    Name[0] = "James";
    Name[1] = "Julian";
    Name[2] = "John";

and so on and to store the 100th name in the array the statement will be:

    Name[99] = "Susan";

NOTE: If array subscript is outside the bounds of the array a runtime error is reported by the compiler.  For example for the Name array,  

    /* This statement will report an exception because the subscript is outside
       the bounds of the array. */
    Name[100] = "Priya"; 

To avoid accidentally overrunning the end of the array in your program, you can test the length of the array by using the length instance variable which is available to all the array objects.

    /*  Name is the array name and the length of this array is assigned to the
        integer variable Len. */  
    int Len = Name.length 

Assignment statement is used to assign a new value to a particular array slot. For example, To change the value contained in the 50th slot in the array Name to "Richie", the statement will be:

    Name[49] = "Richie";

To assign the value contained in 50th slot of array Name to the 3rd slot of the array Name the statement will be:

    Name[2] = Name[49];

One-Dimensional Arrays

One-dimensional array is a list of items represented in the form of an array that has only one subscript. Name is a one-dimensional array.  Given below is the program code, that shows how to create, initialize, modify and display the elements of a one-dimensional array.

    class ArrayDemo
    {
        public static void main(String args[])
        {  
            /* Declaring a one dimensional array numbers */
            int[] numbers; 
            int i;  
             
            /* creating the array numbers to hold 4 integers */
            numbers = new int[4];  
            
            /* Assigning the values to different slots of the array numbers */
            numbers[0] = 20;
            numbers[1] = 2;
            numbers[2] = 11;
            numbers[3] = 32;
             
            /* Displaying the values contained in different slots of array numbers */
            System.out.println(" 1st number in array is "+numbers[0]);
            System.out.println(" 2nd number in array is "+numbers[1]);
            System.out.println(" 3rd number in array is "+numbers[2]);
            System.out.println(" 4th number in array is "+numbers[3]);
        }
    }

Multidimensional arrays

Now we know that array variables can be used to store a list of values.  But what should we do, if we have to store a table of values. For this we use multi-dimensional arrays. Java does not directly support multi-dimensional arrays, but you can create an array of arrays. Suppose we have to store Score1 and Score2 of 4 students.  For this, we cannot use a single dimensional array. For this we have to use a two dimensional array.  The table showing the Score1 and Score2 obtained by the student is shown below:

                       Score1          Score2
    Student1             20              2
    Student2             11              32
    Student3             14              90
    Student4             15              53

The table contains a total of 8 values. This table consists of 4 rows and 2 columns. Each row of this table represents the score obtained by a particular student.  To represent such a table in Java, we can define a two-dimensional array. The table discussed above can be defined as Student[4][2]. The syntax for declaring a two-dimensional array is:

    type array_name[ ][ ];

or,

    type[ ][ ] array_name;

So to declare the two-dimensional array Student we will write the statement:

    int Student[ ][ ];

or,

    int[ ][ ] Student;

The array has been declared but the size of the array has to be set. This is done at the time of creating the array. To create the array and set the size of the array, the syntax is:

    Student = new int[4][2];

Just like one-dimensional array, each dimension of a multi-dimensional array is also indexed from 0 to its maximum size-1.  The table for storing the Score1 and Score2 of the 4 students can be represented in an array in the following form:  

                  Score 1          Score 2
    Student1    20 ([0][0])       2 ([0][1])    
    Student2    11 ([1][0])      32 ([1][1])    
    Student3    14 ([2][0])      90 ([2][1])    
    Student4    15 ([3][0])      53 ([3][1])

Let’s write a program in Java to represent this table of values and display the score obtained by the students. The program is written below: 

    class ArrayDemo
    {
        public static void main(String args[])
        {  
            /* This statement is declaring a two dimensional array i.e. Student
               and it can also be written as  int Student[][]; */
            int[][] Student;
             
            // to create the array Student which will have 4 rows and 2 //columns 
            Student=new int[4][2]; 
             
            /* Assigning the values to the different slots of the array Student */
            Student[0][0] = 20;
            Student[0][1] = 2;
            Student[1][0] = 11;
            Student[1][1] = 32;
            Student[2][0] = 14;
            Student[2][1] = 90;
            Student[3][0] = 15;
            Student[3][1] = 53;
             
            /* Displaying the marks of the students, which are contained in the
               array Student */
            System.out.println(" Score1 of Student1 is: " + Student[0][0]);
            System.out.println(" Score2 of Student1 is: " + Student[0][1]);
            System.out.println(" Score1 of Student2 is:   " + Student[1][0]);
            System.out.println(" Score2 of Student2 is: " + Student[1][1]);
            System.out.println(" Score1 of Student3 is: " + Student[2][0]);
            System.out.println(" Score2 of Student3 is: " + Student[2][1]);
            System.out.println(" Score1 of Student4 is: " + Student[3][0]);
            System.out.println(" Score2 of Student4 is: " + Student[3][1]);
        }
    }
    
Arrays Passed as Arguments to Methods

Arrays are passed by reference to the methods.  This means that changes that occur to the array inside the function, affect the original array.  Given below is an example, which will demonstrate how arrays are passed to the methods:

    class ArrDemo
    {
        public static void main(String args[])
        {
            int arr[] = {1, 6, 3, 1, 0, 1, 34, 1};  
             
            /* pr is defined as an instance or object of class ArrDemo */
            ArrDemo pr = new ArrDemo( );  
            
            for(int i = 0; i < arr.length; i++)
            {
                 /* contents of the array arr are displayed */ 
                System.out.println(arr[i]);  
            }  
             
            /* PassArr function is called, array arr is passed as parameter to
               the function PassArr */             
            pr.PassArr(arr);
            
            System.out.println("new array is ");
             
            for(int i = 0; i < arr.length; i++)
            {  
                /* contents of the array arr are displayed after the function
                   PassArr has been executed */
                System.out.println(arr[i]); 
            }
        }
        
        /* definition of PassArr function */
        void PassArr(int arr[]) 
        {
            for(int i = 0; i < arr.length; i++)
            {
                if(arr[i] == 1)
                {
                    arr[i] = 0;
                }
            }
        }
    }
 
The statement below declares arr as an integer array, and assigns the values contained in { and  }

    int arr[]={1,6,3,1,0,1,34,1};

The following statement calls the function PassArr, to which the array arr is passed as a parameter.  

     pr.PassArr(arr);

Following is the function definition of the function PassArr:

    /* definition of PassArr function */

    void PassArr(int arr[]) 
    {
        for(int i = 0; i < arr.length; i++)
        {
            if(arr[i] == 1)
            {
                arr[i] = 0;
            }
        }
    }

The statement below declares arr[] as a formal parameter, which contains the values contained in the actual argument i.e. arr[] when the function PassArr was called.

    void PassArr(int arr[ ])

The block of statements inside the function finds the value 1 in the array and wherever it finds 1, it substitutes the value 1 with the value 0 in the array.  As the array is always passed by reference in the function, the change in the array is reflected in the main function also. This can be seen by displaying the contents of the array after the function PassArr has executed.  

Ċ
Arrays.pdf
(1065k)
Sukhjit Singh,
Feb 25, 2015, 3:15 PM
Comments