Java arrays

An array is an ordered collections of identical objects that can be accessed via an index. In C and C++, an array is implemented as a contiguous block of memory accessed via pointers to the elements. Java arrays have their own behavior that is encapsulated into their definition when the compiler creates them. Since arrays are objects, array variables behave like class-type variables.

It is important to distinguish between the array variable and the array instance to which it refers. Declaring an array only declares the array variable. To instantiate the array, the new operator must be used with the [] operator to enclose the array size. The array size can be any integer expression. The following code declares an array variable and initializes it to null:

char data[] = null;

This can also be written as:

char[] data = null;

To declare an array variable and initialize it to refer to a new instance, we use the following syntax:

int length = 50;
char[] data = new char [length];

 

Array constants

The declaration of an array must include its type, but not its size. Arrays may be initialized with conventional initialization syntax. An array initializer is either an expression (such as a new expression) that evaluates to the correct array type, or a list of initial element values enclosed in { }. This latter notation is borrowed from C/C++. In Java, this is called an array constant. Any expression can be used for the initial array element values. The following array constant provides initial values for its elements:

int[] int_array = {1, 3, 4, 15, 0};

Each element of an array of class-type objects behaves like a class-type variable:

  • Elements may be allocated by new, making them initially null
  • Elements may be initialized in an array constant
Box b = new Box (2.2, 3.3);
Box[] boxes = { b, new Box (1.1, 2.2) };

NOTE: Java arrays are neither a true class (there is no class called Array), nor a built-in type (arrays have members like a class). Arrays in Java are in between a class and a data type although they are implemented as a class internally by Java.

 

Using arrays

Array elements can be accessed using C notation (an index in square brackets, [n]), where the index must be an integer. Like arrays in C, arrays start with index number 0, not 1. The index can be thought of as an offset from the beginning of the array. The index may not be less than zero or greater than the declared size. If the array is declared size n, the index must be in the range 0 to n-1.

Unlike C, arrays are not implemented as pointers, so programming techniques like negative array indexing are not allowed. Any attempt to index an array with an illegal value will cause an exception to be thrown. All arrays have a data field called length that indicates its size. This value is read-only, and contains the number of elements in the array:

int arr[] = new int[100];
for (int i = 0; i < arr.length; i++) {
   arr[i] = i * i;
}

Since length is read-only, its value cannot be changed manually:

arr.length = 20; // error

 

Copying array elements

The library method System.arraycopy() is useful for copying a number of elements from one array to another. The method can be used on any type of array and is declared as follows:

public static void arraycopy (Object src, int src_position, Object dst, int dst_position, int length)

This method copies elements from the given source array, beginning at the specified position to the destination array at the specified position. It copies the number of elements specified by the length argument. The destination array must already be allocated. Any type of array may be copied. If range exceeds bounds of either array, a run-time error results.

 

Sorting of an one-dimensional array

If the elements of an array are unsorted, we can apply any standard sorting technique to sort them in ascending or descending order. An example of such a sorting technique is Bubble Sort. If this sorting technique takes an array of n elements then it requires at most n-1 iterations to sort them in ascending order. In a series of n-1 iterations, the successive elements, a[j] and a[j + 1] of array ‘a‘ are compared. If a[j] is greater than a[j + 1], then the elements of a[j]  and a[j + 1] are swapped. This process is repeated through until no swaps are necessary. On average, for an array with length ‘n‘, the method takes (n*(n-1))/2 element comparisons. However, by applying “Modified Bubble Sort” (uses a boolean variable as flag), we can avoid unnecessary element comparisons when the array becomes sorted. The time complexity of this sorting technique is O(n2). The code for this technique is shown below:

ArrayTest.java

import java.util.Scanner;

public class ArrayTest {

static void bsort(int a[]) {
int n = a.length;
boolean flag = true;

for(int i=0; iflag==true; i++) {
flag = false;
for(int j=0; j<n-i-1; j++) {
if(a[j]>a[j+1]) {
flag = true;
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size: ");
int size = sc.nextInt();

int a[]; //array declaration
a = new int[size]; //array instantiation

// array initialization
System.out.println("Enter array elements: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}

// apply bubble sort on array
bsort(a);

System.out.println("Display array elements: ");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}

}

Output:

Enter size: 
7
Enter array elements:
86 78 92 67 54 43 32
Display array elements:
32 43 54 67 78 86 92

 

Multidimensional Arrays

So far, we’ve looked at simple arrays that hold their data in a list. However, most programming languages also support multidimensional arrays, which are more like tables than lists. For example, take a look at Figure 1. The first array in the figure is a one-dimensional (1D) array, which is like the arrays we’ve used so far in this chapter. The next type of array in the figure is two-dimensional (2D), which works like the typical spreadsheet type of table we’re used to seeing.

Figure 1: Arrays can have more than one dimension

Although Java doesn’t support multidimensional arrays in the conventional sense, it does enable us to create arrays of arrays, which amount to the same thing. For example, to create a two-dimensional array of integers like the second array in Figure 1, we might use a line of code like this:

 int table[][] = new int[4][4]; 

This line of Java code creates a table that can store 16 values-four across and four down. The first subscript selects the row and the second selects the column. To initialize such an array with values, we might use the lines shown in Listing A (see below), which would give us the array shown in Figure 2.

Figure 2: The 2D array as initialized in Listing A

Listing A : Initializing a Two-Dimensional Array.

table[0][0] = 0;   table[1][0] = 4;   table[2][0] = 8;    table[3][0] = 12; 
table[0][1] = 1;   table[1][1] = 5;   table[2][1] = 9;    table[3][1] = 13; 
table[0][2] = 2;   table[1][2] = 6;   table[2][2] = 10;   table[3][2] = 14; 
table[0][3] = 3;   table[1][3] = 7;   table[2][3] = 11;   table[3][3] = 15;

 

Creating a two-dimensional (2D) array

Suppose that we need a table-like array that can hold 12 integers in 3 rows and 4 columns. First, we’d declare the array like this:

int data[][];

After declaring the array, we need to create it in memory, like this:

data = new int[3][4];

The last step is to initialize the array, probably using nested for loops:

for (int x=0; x<3; ++x)  {    
   for (int y=0; y<4; ++y)  {           
       data[x][y] = 0;     
    }
}

The code below initializes the data[ ][ ] array to all zeroes.

Array2D.java

public class Array2D {
public static void main(String[] args) {
int data[][];
data = new int[3][4];
for (int x=0; x<3; ++x) {
for (int y=0; y<4; ++y) {
data[x][y] = 0;
}
}
System.out.println("Row Size = " + data.length);
System.out.println("Column Size = " + data[0].length);
}
}
Output:
Row Size = 3
Column Size = 4

 

 

Accessing elements of a two-dimensional (2D) array

Suppose that a 2D array of int values is initialized, and all the elements of the array are accessed using nested for loops. See the example below:

Test2Darray.java

public class Test2Darray {

public static void main(String args[]) {
int[][] a = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 }
};
int rows = a.length;
int cols = a[0].length;
System.out.println("Printing Matrix a");
System.out.println("-----------------");
System.out.println("array["+rows+"]["+cols+"] = {");
for (int i=0; i<rows; i++) {
System.out.print("{");
for (int j=0; j<cols; j++)
System.out.print(" " + a[i][j] + ",");
System.out.println("},");
}
System.out.println("};");
System.out.println();
}
}
Output:
Printing Matrix a
-----------------
array[2][4] = {
{ 1, 2, 3, 4,},
{ 5, 6, 7, 8,},
};

 

 

Matrix multiplication of two 2D arrays

The example below shows the matrix multiplication of two 2D arrays.

Matrix.java

public class Matrix {

/* Matrix-multiply two 2D arrays together.
* The arrays MUST be rectangular.
*/
public static int[][] multiply(int[][] m1, int[][] m2) {
int m1rows = m1.length;
int m1cols = m1[0].length;
int m2rows = m2.length;
int m2cols = m2[0].length;
if (m1cols != m2rows) {
System.out.println("Matrix multiplication not possible");
System.exit(0);
}
int[][] result = new int[m1rows][m2cols];
// multiply
for (int i=0; i<m1rows; i++)
for (int j=0; j<m2cols; j++)
for (int k=0; k<m1cols; k++)
result[i][j] += m1[i][k] * m2[k][j];

return result;
}

/** Matrix print.
*/
public static void mprint(int[][] a) {
int rows = a.length;
int cols = a[0].length;
System.out.println("array["+rows+"]["+cols+"] = {");
for (int i=0; i<rows; i++) {
System.out.print("{");
for (int j=0; j<cols; j++)
System.out.print(" " + a[i][j] + ",");
System.out.println("},");
}
System.out.println("};");
System.out.println();
}

public static void main(String[] args) {
int x[][] = {
{ 3, 2, 3 },
{ 5, 9, 8 },
};
int y[][] = {
{ 4, 7 },
{ 9, 3 },
{ 8, 1 },
};
int z[][] = Matrix.multiply(x, y);
System.out.println("Matrix One:-> Printing Matrix x");
System.out.println("-------------------------------");
Matrix.mprint(x);
System.out.println("Matrix Two:-> Printing Matrix y");
System.out.println("-------------------------------");
Matrix.mprint(y);
System.out.println("Mul Result:-> Printing Matrix z");
System.out.println("-------------------------------");
Matrix.mprint(z);
}
}

Output:

Matrix One:-> Printing Matrix x
-----------------------------------
array[2][3] = {
{ 3, 2, 3,},
{ 5, 9, 8,},
};

Matrix Two:-> Printing Matrix y
-----------------------------------
array[3][2] = {
{ 4, 7,},
{ 9, 3,},
{ 8, 1,},
};

Mul Result:-> Printing Matrix z
----------------------------------
array[2][2] = {
{ 54, 30,},
{ 165, 70,},
};