Arrays in Java

In this post, you will learn to:

  • Define an array.
  • Explain single-dimensional arrays.
  • Describe two-dimensional arrays.
  • Explain searching and sorting in arrays.

Need of an Array

Variables can be used to store and manipulate values. Only one value can be stored in one variable at one point in time. This means that in case you need to store 20 values of the same type you need to define 20 variables for holding those values. The problem here is that a lot of memory is consumed for defining and initializing every single variable. Besides, values are not stored in the contiguous area of memory, that is, they are not stored sequentially. A single loop cannot be used to access and manipulate the values.

Definition

An array is a special data store that can hold several items of a single data type in contiguous memory locations.

For example, a class teacher needs to store the scores of 30 students in a class and calculate grades for each of them. The data that needs to be stored is of uniform type. This means that the scores of all the students would be stored as integers. However, it would be a tedious process to define 30 integer variables for storing the scores. This is where the concept of arrays comes in. You can declare an array of size 30 and of data type int that can store 30 integer values.

The figure below shows the allocation of an integer array in memory.

Structure

Arrays are the best means of manipulating data that is available in the form of a collection. All the elements within an array must belong to the same data type.

Array have a single name and each of the elements in the array is accessible through an integer value called a subscript. Using the integer subscript, the array elements are accessed quickly and efficiently. An array subscript begins from zero and is also called an array index. The size of an array is the maximum number of elements that an array can hold. If during processing of an array, the value of array subscript exceeds this size, Java will throw runtime exception, and the program will abort immediately. Exception is an abnormal error condition in a program.

Benefits of using Arrays:

  • Arrays are the best means of operating on multiple data elements of the same type at the same time.
  • Arrays make optimum use of memory resource as compared to variables.
  • Memory can be assigned to an array only at the time when the array is actually used. Thus, the memory is not consumed by an array right from the time you declare it.

Single-dimensional Arrays

Arrays in Java are of two types: single-dimensional and multi-dimensional. Single-dimensional arrays can have only one dimension and are visually represented as having several rows but a single column of data. Multi-dimensional arrays can have more than one dimension, but typically two or three dimensions are used. Memory can be allocated to an array variable by using the new operator.

The figure below shows the allocation of single-dimensional array in memory.

The following is the syntax for declaring a single-dimensional array.

Syntax:

datatype[] arrayName = new datatype[size];

where,
datatype: any valid data type in Java
[]: denotes that the variable is an array
arrayName: array variable that will refer to the array
new: allocates memory for objects
size: number of elements that can be stored in an array.

The following code shows the declaration for a single-dimensional integer array.

Code Snippet:

int[] studentScores = new int[25];

This declares an integer array with 25 elements.

Note: An array having four columns is not called a four-dimensional array; it is still a two-dimensional array. The number of subscripts needed to access elements depends upon the dimensions of an array

Store and Display Values

An array can be initialized at the time of declaration or after declaration at the time of specifying the size of the array. The important point is that in order to use an array, it has to be declared and instantiated. The various ways to initialize and display array elements are as follows:

Initialize individual array elements

After initializing the array, the next step is to assign values to the array elements. Since, an array is a collection of multiple elements, you have to assign values to every array element specifically. The following code demonstrates how to initialize and assign values to an array of integers called studentScores.

Code Snippet:

int[] studentScores = new int[5];
studentScores[0] = 45;
studentScores[1] = 75;
studentScores[2] = 63;
studentScores[3] = 25;
studentScores[4] = 89;

To assign a value to an array element, you need to specify the array element with its index.

Use Loop to Initialize

The values for array elements can be accepted using the methods of the Scanner class or other ways with one or more loops as per the requirements. The length property can be used to find the total number of elements in an array. The following code demonstrates how to accept values in an array using for loop.

Code Snippet:

int count; //counter variable;
float[] itemRate = new float[3]; //array itemRate
float total = 0; //total variable
Scanner input = new Scanner(System.in);

for(count = 0;count < 3;count++)
{
   System.out.println("Enter Item rate: ");
   itemRate[count] = input.nextFloat(); //enter item rate    
   total = total + itemRate[count]; //calculate total
}
 
System.out.printf("Total of all item rates is %.2f",total);    //prints total
System.out.println("\nLength of the array is " +itemRate.length);    // prints the length

To hold the sum of item rates in terms of fractional numbers, an array, itemRate, is declared of type float and the total variable is initialized to zero. The Scanner class object allows you to accept values from the user with the help of the for loop. This loop begins from zero and accepts values as long as the condition count < 3 evaluates to true.

Within the loop, the nextFloat() method is used to accept values from the user for item rates.The item rate adds to the current value of total to provide total value. Once the value of count reaches 3, the loop execution stops and the value of total and length of the array is printed.

Display Array (simple loop)

Retrieving data from arrays is done by accessing the array elements by specifying the array index and using the value stored at that position in the array. The following code shows how to retrieve the value of the fifth array element of an integer array called numArray.

Code Snippet:

int num;
num = numArray[4];

The following code demonstrates displaying of array values using a for loop.

Code Snippet:

int count;   //counter variable;
// code for accepting array values from user
...
//Displaying array values
for(count = 0; count < rollNumber.length; count++)
{
   System.out.printf("\nRollNumber:%d", rollNumber[count]);
}

In the code, it is assumed that an array called rollNumber is created for storing integer values.At the end of the program, all the values stored in the array are displayed to the user using a for loop.

Display Array (for-each loop)

The for-each loop in Java 1.5 is a new way of iterating over arrays. This new for statement is called the enhanced for or for-each loop. The following is the syntax of for-each loop.

Syntax:

for(type variable : array){
   statement(s);
}

The following code demonstrates the use of for-each loop in Java 1.5.

Code Snippet:

double sum= 0;
double[] numArray = {10.12, 67.99, 56.65, 45.43, 32.45};

System.out.println("Array Values are: ");
//for-each loop
for(double index : numArray){ 
   System.out.println(index);
   sum += index;
}
System.out.println("Sum = "+ sum);

The numArray array variable is declared and initialized with a few double values. The for-each loop is used to iterate over the array. The array value at the current subscript is displayed and the value is added to the variable, sum, with each iteration.

Two-dimensional Arrays

Two-dimensional arrays (2D arrays) are arrays having more than one dimension. Although it is possible to create three and higher dimensional arrays, two-dimensional arrays are commonly used. Two-dimensional arrays too have subscripts beginning from zero onwards. Therefore, in a 2D array,the first element is stored at arrayName[0][0] (where [0][0] is the row and column subscript), the second element at arrayName[0][1] and so on. Maximum number of array elements in a 2D array is rowSize*columnSize.

The figure below shows the allocation of two-dimensional array in memory.

The following is the syntax for declaring a two-dimensional array.

Syntax:

datatype[][] arrayName = new datatype[rowsize][colsize];

where,
datatype: is any valid datatype in Java.
rowsize and colsize: are the number of rows and columns that the array will contain respectively.rowsize and colsize need not be the same. They must be positive integer values or constants containing positive integer values.
The new operator is used to allocate memory to the array elements.

The following code demonstrates the declaration for a 2D array.

Code Snippet:

int[][] matrix_num = new int[4][2];

This declares matrix_num to be an array of type int, which will contain maximum 4 rows and 2 columns.The maximum number of elements that can be stored in this array is 4 x 2 = 8 elements.

Use Loop to Initialize

An array can be initialized at the time of declaration or after declaration at the time of specifying the size of the array. The figure below shows the accessing of an element at a particular index from a 2D array.

Two-dimensional arrays can be initialized in the following ways:

Assigning individual array elements

The following code declaration assigns value for three subjects for two students in the array, stuMarks.

Code Snippet:

//initializes an integer array with 2 rows and 3 columns
int[][] stuMarks = new int[2][3];
stuMarks[0][0] = 55;
stuMarks[0][1] = 45;
//assignment of remaining elements
...
stuMarks[1][2] = 98;

At the time of declaration

The following code snippet shows how to initialize values of an array at the time of declaration.

Code Snippet:

int[][] stuMarks = {{55,45,23}, {78,67,98}};

Using a looping construct

The following code shows the use of loop construct to accept values for the user and storing them in the array elements.

Code Snippet:

int[][] stuMarks = new int[2][3]; //array with 2 rows and 3 //columns
int rowIndex = 0;
int colIndex = 0;
Scanner input = new Scanner(System.in);
int[][] stuMarks = new int[2][3]; //array with 2 rows and 3 columns
int rowIndex = 0;
int colIndex = 0;
Scanner input = new Scanner(System.in); 
//row increment
for(rowIndex= 0;rowIndex < stuMarks.length;rowIndex++)
{
   //column increment
for (colIndex=0;colIndex<stuMarks[rowIndex].length;colIndex++)
   {
      System.out.println("Enter value: ");
      //accepting array values
      stuMarks[rowIndex][colIndex] = input.nextInt();
   }
}

The code defines a two-dimensional 2X3 array, stuMarks. Further, it declares index variable for the rows and columns of array. The code uses two for loops: one for the rows and one for the columns. The outer loop executes as long as the value of subscript, rowIndex, is less than two and the inner loop executes as long as the subscript value, colIndex, is less than or equal to three.

The length property is used to find the total number of rows and columns in a two-dimensional array. In the code snippet, if you give stumarks.length, it will print only the total number of rows. If you want to get the total number of columns, the stuMarks[currentrowindex].length can be used.

Display Array Values

The array elements of a two-dimensional array can be printed individually or by using loops. The following code demonstrates the creation of an array with two rows and two columns, puts some values in it, and prints each value to standard output.

Code Snippet:

int[][] stuMarks = new int[2][2]; //array with 2 rows and 2 columns
stuMarks[0][0] = 45;
// remaining elements
...
stuMarks[1][1] = 86;
System.out.println("Element at row 0 column 0: "+stuMarks[0][0]);
System.out.println("Element at row 0 column 1: "+stuMarks[0][1]);
System.out.println("Element at row 1 column 0: "+stuMarks[1][0]);
System.out.println("Element at row 1 column 1: "+stuMarks[1][1]);

The following code assigns values to a two-dimensional array and prints it using a nested for loop.

Code Snippet:

int[][] stuMarks = new int[2][2]; //array with 2 rows and 2 columns
int rowIndex = 0;
int colIndex = 0;

// code for accepting values in a 2D array
...
// displaying values of a 2D array elements
//row index
for(rowIndex= 0;rowIndex < stuMarks.length;rowIndex++){
   //column index
   for (colIndex=0;colIndex<stuMarks[rowIndex].length;colIndex++){
      //display values
      System.out.printf("\nArray value at [%d, %d] = %d ",rowIndex,colIndex,stuMarks[rowIndex][colIndex]);
   }
}

As shown in the code, the values stored in the array are displayed to the user by using a loop structure.

Sorting in Arrays

It is often necessary to arrange the elements in an array in numerical order from highest to lowest values (descending order) or vice versa (ascending order). The process of sorting an array requires exchange of value. There are many different ways to sort arrays.The basic goal of all these methods is the same. They compare each array element to another array element and exchange them if they are in the wrong position.

The exchange sort process starts at the beginning of the set of values. This type of sorting compares the first element with each following element in the array and makes necessary swaps. This ends the first pass. Then it takes the second element and compares it with each following element in the array, making necessary swaps. This repeats until no swaps have occurred on the last pass.

The figure below demonstrates the concept of exchange sort.

The table below shows the array elements sorted in descending order after every pass. A pass is defined as one full trip through the array comparing, and if necessary, swapping elements.

Original Array Values 65 10 57 98 105 304
After Pass 1 304 10 57 65 98 105
After Pass 2 304 105 10 57 65 98
After Pass 3 304 105 98 10 57 65
After Pass 4 304 105 98 65 10 57
After Pass 5 304 105 98 65 57 10

The first two data items (65 and 10) are compared and the larger value is placed on the left hand side. In this case, 10 is less than 65; hence no swapping is done. Next, the first and third elements (65 and 57) are compared and here also, no swapping takes place. Then the first and fourth elements (65 and 98) are compared and the swapping is done. After the comparison is over with all the remaining elements in the array, the largest data item (304) is placed at the beginning of the list. At the end of the second pass, the second largest data item (105) will be in the second position. The process continues and the smallest item is placed at the end of the list.

The following code shows the actual Java code for sorting the elements in descending order.

Code Snippet:

int[] array = {65, 10, 57, 98, 105, 304};
int i, j;
int temp;
//array length
int arrayLength = array.length;
//element to be compared is identified in this loop
for (i = 0;i < (arrayLength -1);i++) {
   //represents the rest of the elements
   for(j = (i+1);j < arrayLength;j++) {
      if (array[i] < array[j]) {
         //swapping elements
         temp = array[i];
         array[i] = array[j];
         array[j] = temp;
      }
   }
}

//display array values after sorting
for(i = 0;i < array.length;i++) {
   System.out.print(array[i] + “\t”);
}

The output of the code is displayed as follows:

304    105    98    65    57    10

Searching in Arrays

There are various ways to search for an array value. Of all the search methods, sequential search is the simplest and easiest to implement. In sequential search, the search value is compared with the array values starting with the first element. Since the search is performed in a linear fashion, this method is also called as linear search. This is performed on an unsorted array, and is slow.

The most effective technique that can be applied to sorted records in an array is the binary search technique. This technique is faster than any other search method. This technique checks the element in the middle of the array. If the search value is equal to the middle element, the search is finished. If the search value is less than the middle element, then a binary search on the first half of the array is performed. If it is greater, then a binary search of the second half of the array is carried out. Before performing a binary search, the array must be sorted.

The figure below shows the binary search technique to search an element in a sorted array. The search value here is 11.

The following code demonstrates the Java code for doing a binary search.

Code Snippet:

int[] array = {0, 11, 13, 14, 15, 17, 18, 19, 21, 24, 26, 28 , 29};
int low = 0;
int high = array.length - 1;
int searchValue = 11; // key value to search
int flag = 0; // flag variable to check the status
while (low <= high) {
   int mid = low + (high - low) / 2; // Compute mid point
   if(searchValue == array[mid]){
      flag = 1;
      System.out.println(“Element found at index “+ mid);
      break;
   } else if (searchValue  array[mid]){
      low = mid + 1; // repeat search in second half
      } // end of else
} // end of while

if(flag == 0){
   System.out.println(“Element not found in the array”);
}

The output of the code is as follows:

Element found at index 1
Related Post