The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Arrays and Vectors

Introduction to Arrays
Suppose you want to store the marks of 100 students and then find the average. Would you declare 100 variables for that ? Definitely not. So, here comes a data structure called array which provides an utility to store a collection of elements of same data type in contiguous memory location.
Consider the declaration below :

int marks[ ] = new int[5]; // declaration and instantiation of the array

In the above statement, we have declared and instantiated an array named marks which can store 5 values of type int. Each of the values can be accessed using an index in the array.
Suppose there are 5 values stored in the array marks as show below :

7562934988

Value stored at index 0 of array marks is 75 i.e marks [ 0 ] = 75. Remember array index starts from 0.
Similarly, marks [ 2 ] = 93. The array marks can be initialized with 5 values in a single statement :

int marks[ ] = { 75, 62, 93, 49, 88 }; // declaration, instantiation and initialization of the array

Let's look at a very simple program which illustrates the declaration, instantiation and initialization of an array :

public class ArrayDemo {
   public static void main(String args[]) {
      int arr[]; // declaration ( can be written as 'int[] arr;' also )
      arr = new int[3]; // instantiation ( we can store 3 int values )
      arr[0] = 7; arr[1] = 4; arr[2] = 5; // initialization

      /* Single statement which does all the three steps :-
       * int arr[] = {7, 4, 5};
       */

      /* traverse and print the array elements
       * 'length' is the property of an array
       */
      System.out.println("Printing array elements");
      for ( int i = 0; i < arr.length; i++ ) {
         System.out.println(arr[i]);
      }

      /* we can also traverse the array using 'foreach' loop */
      System.out.println("Printing array elements again");
      for (int element : arr) {
         System.out.println(element);
      }
   }
}


Passing array to method
Similar to other data types, we can also pass an array to a method. Following program searches an element in array and returns its position if found.

public class ArrayPassingDemo {

   /* Search an element 'var' in the array
    * Return the position (index) if element is found else return -1
    */
   static int searchElement(int arr[], int val) {
      int pos = -1;
      for ( int i = 0; i < arr.length; i++ ) {
         if (arr[i] == val) { // compare each array element with 'var'
            pos = i; // element found
            break; // break out of loop
         }
      }
      return pos;
   }

   public static void main(String args[]) {
      int arr[] = { 56, 43, 12, 9, 39 };
      int pos = searchElement(arr, 9); // search element '9'
      if (pos != -1) {
         System.out.println("Element is found at position : " + pos);
      }
      else {
         System.out.println("\nElement not found ... ");
      }
   }
}


Returning array from method
Next we illustrate how to return an array from method. In the following program, a method takes an array as argument and returns another array in which every element is multiplied by 10.

public class ArrayReturnDemo {

   static void display(int arr[]) {
      for ( int element : arr ) {
         System.out.print(element + " ");
      }
   }

   static int[] getNewArray(int arr[]) {
      int aux_array[] = new int[arr.length];
      for ( int i = 0; i < arr.length; i++ ) {
         /* multiply each element by 10 */
         aux_array[i] = arr[i] * 10;
      }
      return aux_array;
   }

   public static void main(String args[]) {
      int arr[] = { 56, 43, 12, 9, 39 };
      int new_arr[] = getNewArray(arr);
      System.out.print("arr : ");
      display(arr);
      System.out.println();
      System.out.print("new_arr : ");
      display(new_arr);
   }
}


2-Dimensional Arrays ( Matrix )
So, far we have seen one dimensional arrays. Now we will see two dimensional array also known as matrix, which is another useful data structure. Consider the declaration below :

int mat[ ][ ] = new int[3][4];

We have declared and instantiated a two dimensional array or matrix with 3 rows and 4 columns. We can store
3 x 4 = 12 elements in this matrix. Each element is stored in a cell which can be accessed using the combination of row index and column index. Initialization of a 2D array is shown below :

InitializationIndexing
int mat[3][4] = { { 17, 23, 15, 19 },
                  { 44, 29, 52, 76 },
                  { 21, 63, 35, 57 } };

17 [ 0, 0 ]23 [ 0, 1 ]15 [ 0, 2 ]19 [ 0, 3 ]
44 [ 1, 0 ]29 [ 1, 1 ]52 [ 1, 2 ]76 [ 1, 3 ]
21 [ 2, 0 ]63 [ 2, 1 ]35 [ 2, 2 ]57 [ 2, 3 ]

We can see how the above initialization statement in the left builds a matrix shown in the right. Every element is stored in a cell which has a index shown as subscript of each element. For e.g, 52 is stored in a cell with index
[ 1, 2 ] where 1 denotes the row number ( index ) and 2 denotes the column number ( index ). Please note that both row and column index starts with 0.
Following program illustrates declaration, instantiation and initialization of a matrix :

public class MatrixDemo {
   public static void main(String args[]) {
      int rows = 3, cols = 3;
      int mat[][]; // declaration ( can be written as 'int[] arr;' also )
      mat = new int[rows][cols]; // instantiation (we can store 3x3 = 9 values)

      /* initialize the 2d array elements */
      int x = 1;
      int i, j;
      for ( i = 0; i < rows; i++ ) { // outer loop iterates over each row
         for ( j = 0; j < cols; j++ ) { // inter loop iteartes over each column
            mat[i][j] = x; // i -> row no. and j -> col no.
            x++;
         }
      }
      /* print the 2d array elements */
      for ( i = 0; i < rows; i++ ) {
         for ( j = 0; j < cols; j++ ) {
            System.out.print(mat[i][j] + " ");
         }
         System.out.println();
      }
   }
}


Passing 2D array to method
Following program illustrates how to pass 2D array to methods :

public class MatrixPassingDemo {

   /* computes the sum of left diagonal elments */
   static int sumLeftDiagElements(int mat[][]) {
      int i, j, sum = 0;
      int rows = mat.length; // get the no. of rows
      int cols = mat[0].length; // get the no. of cols
      for ( i = 0; i < rows; i++ ) {
         for ( j = 0; j < cols; j++ ) {
            if ( i == j ) { // we found a left diagonal element
               sum += mat[i][j];
            }
         }
      }
      return sum;
   }

   /* computes the sum of right diagonal elments */
   static int sumRightDiagElements(int mat[][]) {
      int i, j, sum = 0;
      int rows = mat.length; // get the no. of rows
      int cols = mat[0].length; // get the no. of cols
      for ( i = 0; i < rows; i++ ) {
         for ( j = 0; j < cols; j++ ) {
            if ( (i + j) == (rows - 1) ) { // we found a right diagonal element
               sum += mat[i][j];
            }
         }
      }
      return sum;
   }

   public static void main(String args[]) {
      int mat[][] = { { 2, 3, 8, 4 },
                      { 5, 1, 7, 3 },
                      { 9, 2, 6, 8 },
                      { 1, 4, 5, 7 } };
      int sum_left_diag = sumLeftDiagElements(mat);
      int sum_right_diag = sumRightDiagElements(mat);
      System.out.println("Sum of left diag elemnts = " + sum_left_diag);
      System.out.println("Sum of right diag elemnts = " + sum_right_diag);
   }
}


Returning 2D array from method
Following program illustrates how to return 2D array from methods :

public class MatrixReturnDemo {

   static void display(int mat[][]) {
      for ( int i = 0; i < mat.length; i++ ) {
         for ( int j = 0; j < mat[0].length; j++ ) {
            System.out.print(mat[i][j] + " ");
         }
         System.out.println();
      }
   }

   static int[][] getNewMatrix(int mat[][]) {
      int rows = mat.length;
      int cols = mat[0].length;
      int aux_mat[][] = new int[rows][cols];
      for ( int i = 0; i < rows; i++ ) {
         for ( int j = 0; j < cols; j++ ) {
            /* multiply each element by 10 */
            aux_mat[i][j] = mat[i][j] * 10;
         }
      }
      return aux_mat;
   }

   public static void main(String args[]) {
      int mat[][] = { { 2, 3, 8 },
                      { 5, 1, 7 },
                      { 9, 2, 6 } };
      int new_mat[][] = getNewMatrix(mat);
      System.out.println("mat : ");
      display(mat);
      System.out.println("new_mat : ");
      display(new_mat);
   }
}


Vectors
The main limitation of array is size limit. We can store only fixed number of elements in the array and the size cannot be grown at runtime. Vector introduces the concept of dynamic array in Java. Vector is a class contained in java.util package and it can hold any number and any type of objects. The only limitation is that it can't hold elements of primitive data types like int, float, char, double, long and boolean, we can only store objects. So, the elements need to be converted to objects before storing them in vector. This can be done using wrapper classes contained in java.lang package. For e.g Integer is a wrapper class to convert an int type element to an object. Following set of statements explain how int type element is converted to Integer object and vice versa.

int val = 10; /* declare a variable of integer type */
Integer int_obj = new Integer(val); /* convert 'val' to an object which
                                     * is referenced by 'int_obj */

int i = int_obj.intValue(); /* convert object to int data type */

Following table shows the list of wrapper classes which are used to convert primitive data types to objects :

Primitive Data TypeWrapper Class
intInteger
charCharacter
longLong
floatFloat
doubleDouble
booleanBoolean

Let's look at a program demonstrating the use of Vector class.

import java.util.*;
public class VectorDemo {
   public static void main(String args[]) {
      Vector v = new Vector(); // Create an object of vector class
      v.addElement(new Integer(5)); /* Convert 5 to an object and
                                     * add it to the vector */
      v.addElement(new Float(3.67f)); // add a float value to 'v'
      v.addElement(new Double(4.53));

      System.out.println("Vector Size : " + v.size());
      int first_element = (Integer)v.firstElement();
      System.out.println("First Element : " + first_element);

      /* print all the elements of the vector */
      Enumeration v_enum = v.elements(); // enumerate the elements
      System.out.print("\nElements : ");
      while(v_enum.hasMoreElements()) {
         System.out.print(v_enum.nextElement() + "  ");
      }
      System.out.println();
   }
}

Vector class has lot of methods. In the above program, we have used addElement( ), size( ) and firstElement( ). Please refer to the documentation of Vector to know about all the methods. Some of the commonly used methods are shown in the table below :

MethodDescription
addElement(item)Add an item to the end of the vector
size()Get the no. of objects present in the vector
removeElement(item)Removes the specified item from the vector
removeElement(pos)Remove the item stored at specified position
insertElementAt(item, pos)Insert item at specified position
copyInto(array)Copy the vector elements into array

Back | Next