Java Arrays With Examples

Introduction

In our previous lectures, we have discussed the primitive data types and their corresponding Wrapper classes. Storing multiple entities in different variables is very difficult to identify and manage. We are going to introduce a new data structure called Array which is a sequential collection of the same data types. So a single variable can store multiple data references. As mentioned, array allocates a sequential memory block and is static(fixed-length) in nature.

Let us take an example:

int a = 3;
int b = 6;
int c = 9;
int d = 12;
int e = 15;

Instead of storing the values of multipliers of 3 in different variables, we can have a single variable ( say table3 ) to store all of it in a single array.

Along with array, we have an index. Each and every data is available in a different position.

The index positions start from 0.

So in order to access, we call for table3[indexPosition]. To access 3 we pass 0 in place of index position inside square brackets i.e table3[0] = 3. Similarly, table3[1] = 6 , table3[2] = 9, table3[3] = 12, table3[4] = 15, table3[5] = 18 and soon.

Array Creation

In order to create an array, we need to declare the variable followed by assigning the reference of the newly created variable to the declared variable.

1. Array Variable declaration

dataType[] myArray;  //Reccommended
dataType myArray[]; //available for C/C++ programmers to adopt java in its initial days

The dataType signifies the data type of its unit member i.e if we want a collection of integers we write int [] array. We can create an array of any data type(primitive and referential).

We are going to use the recommended format throughout our lecture.

Example:

int[] myIntArray;          //Array of integers
float[] myFloatArray;      //Array of floats
double[] myDoubleArray;    //Array of doubles

2. Creating an array reference and assigning:

For the creation of the array reference, we are going to use the new operator. The format is as follows:

new DataType[arraySize];

The arraySize defines how many elements can this array hold. The index ranges from 0 to arraySize-1.

Example:

new int[10]; //this array can hold 10 integers
new float[5]; //this array can hold 5 floats

There is one more process. We can pass our data element inside curly brackets.

Example:

{3, 6, 9, 12, 15, 18, 21, 24, 27, 30};

This creates an array of size (number of elements passed inside braces) and data type(the data type of unit elements).

3. Assignment of created array reference to the variable

We are simply combining the output of the above steps

int[] myIntArray = new int[10];    //This creates an array of size 10 ,each element being 0 and index ranges from 0 to 9
int[] myIntArray = {3, 6, 9, 12, 15, 18, 21, 24, 27, 30}; //This creates an array of size 10 with the values mentioned and index ranges from 0 to 9.

Example:

public class MyArrayClass {
    public static void main(String[] args) {
        
        int[] myArray1 = new int[10];   //Creation of an array using new
        int[] myArray2 = {3,6,9,12,15,18,21,24,27,30};  //Creation of an array by diretly passing data elements
        
        
        System.out.println("Element at myArray2[5] is "+myArray2[5]+"\n");
            
         //This is a loop statement [We will learn this in Java loops. 
         //As of now consider it as a block to print the contents of an array]
        System.out.println("Contents of myArray1");
        for(int i=0;i<myArray1.length;i++)
        {
            System.out.print(myArray1[i]+" ");
        }
        
        System.out.println("\n\nContents of myArray2");
        for(int i=0;i<myArray2.length;i++)
        {
         System.out.print(myArray2[i]+" ");   
        }  
        
        
        System.out.println("\n\nWe can even change the element at any position");
        System.out.println("(Before)Element at myArray2[7] is "+myArray2[7]);
        myArray2[7]=999;   // changing the value of data at any desired index( in this case 7)
        System.out.println("(After)Element at myArray2[7] is "+myArray2[7]);
    }
    
}

Output:

Element at myArray2[5] is 18

Contents of myArray1
0 0 0 0 0 0 0 0 0 0 

Contents of myArray2
3 6 9 12 15 18 21 24 27 30 

We can even change the element at any position
(Before)Element at myArray2[7] is 24
(After)Element at myArray2[7] is 999

2D Array

We have been discussing an array which is linear[single dimensional array]. By single dimension we mean, to access any specific element, we need only one index. Java has provisions to create multi-dimensional arrays are well. For clarity, we are going to discuss a two-dimension array. Let us see the following illustration :

2D Array.png

The data is stored in rows and columns in a 3 by 3 grid. We can visualize the 2-D array as an array of array. Each index of the main array(row) stores the reference of an array of 3 data(as given in the diagram). We can understand it this way.

Say, we have 3 arrays 

   A    B    C

 

   D    E    F

 

   G    H    I

We create an array that keeps the reference of these 3 arrays and that is what we call a 2 D array.

So in order to access an element say F, we know that it is available as 3rd element of the 2nd array.

Hence,  my2DArray[1][2] = ‘F’  (Index start from 0, and not 1)

Here 1 inside the first square bracket indicates the element belongs to the array reference is available at index position 1. 2 in the second square bracket indicates that the element is positioned at index 2.

2D Array Creation

1. Using new keyword

The parameters rowSize and colSize indicate the number of rows and columns in which the data will be positioned.

 dataType[][] my2DArray = new dataType[rowSize][colSize];

Example:

char[][] my2DArray = new char[3][3];

2. Directly by specifying elements

char[][] my2DArray = {

{'A', 'B', 'C'},

{'D', 'E', 'F'},

{'G', 'H', 'I'}

}

Example:

public class MyArrayClass {
    public static void main(String[] args) {
        
        char[][] myArray1 = new char[3][3];   //Creation of an array using new
        char[][] myArray2 = { 
                            {'A','B','C'},
                            {'D','E','F'},
                            {'G','H','I'}
                          };  //Creation of an array by diretly passing data elements
        
        
        System.out.println("Element at myArray2[1][2] is "+myArray2[1][2]+"\n"); // The data explained with
        
         //This is a loop statement [We will learn this in Java loops. 
         //As of now consider it as a block to print the contents of an array]
        System.out.println("Contents of myArray1");
        for(int i=0;i<myArray1.length;i++)
        {
            for(int j=0;j<myArray1[0].length;j++)
            {
                System.out.print(myArray1[i][j]+" ");
            }
            System.out.println();
        }
        
        
        System.out.println("Contents of myArray2");
        for(int i=0;i<myArray2.length;i++)
        {
            for(int j=0;j<myArray2[0].length;j++)
            {
                System.out.print(myArray2[i][j]+" ");
            }
            System.out.println();
        }
    }
}

Output:

Element at myArray2[1][2] is F

Contents of myArray1
. . .
. . .
. . .

Contents of myArray2
A B C 
D E F 
G H I 

Arrays Class

Java comes with a class dedicated to facilitating all sorts of manipulations(sorting and searching). This class is Arrays(part of java.util package).  The class comes loaded with a huge range of array processing. We are going to explore a few of them(copyToRange and sort) to show how easy does it makes the overall process.

Example:

import java.util.Arrays; //The package has been imported
public class MyArrayClass {
    public static void main(String[] args) {
        

        int[] myArray = {3,27,24,21,18,15,9,12,30,6}; 
        
        
         //This is a loop statement [We will learn this in Java loops. 
         //As of now consider it as a block to print the contents of an array]

        System.out.println("Contents of myArray");
        for(int i=0;i<myArray.length;i++)
        {
         System.out.print(myArray[i]+" ");   
        }  
        
        
        System.out.println("\n\n\n*************Copying an Array with Specified range****************");
        
         /*The method copyOfRange() takes 3 inputs
        1)the source array
        2)from index
        3)to index
        The function takes the input and copies the array from specified index and returns the refernce of the newly created array
        */
        int[] myCopyofArray = Arrays.copyOfRange(myArray,0,5); 
        
        


         //This is a loop statement [We will learn this in Java loops. 
         //As of now consider it as a block to print the contents of an array]
        System.out.println("Contents of myCopyofArray[Copied the myArray from index 0 to 5]");
        for(int i=0;i<myCopyofArray.length;i++)
        {
         System.out.print(myCopyofArray[i]+" ");   
        }


        //SORTING
        System.out.println("\n\n\n******************************Sorting*****************************");
        
        System.out.println("(Before Sorting)Contents of myArray");
        for(int i=0;i<myArray.length;i++)
        {
         System.out.print(myArray[i]+" ");   
        } 
        
        /*The Method sort() takes 1 input
        1)The Array that needs to be sorted
        This method sorts the array in ascending order
        */
        Arrays.sort(myArray);
        System.out.println("\n\n(After Sorting)Contents of myArray");
        for(int i=0;i<myArray.length;i++)
        {
         System.out.print(myArray[i]+" ");   
        } 
        
       
    }
    
}

Output:

Contents of myArray
3 27 24 21 18 15 9 12 30 6 


*************Copying an Array with Specified range****************
Contents of myCopyofArray[Copied the myArray from index 0 to 5]
3 27 24 21 18 


******************************Sorting******************************
(Before Sorting)Contents of myArray
3 27 24 21 18 15 9 12 30 6 

(After Sorting)Contents of myArray
3 6 9 12 15 18 21 24 27 30 

This was an overview of Java Arrays. We will discuss reserved keywords in our next lecture.