Array Operations in Java


Like C and C++, array is a very useful structure in Java programming language too. There are several useful operations, provided by the Java programming language that you can perform on arrays. In this lesson we will show you some of the very useful array operations in java programming language.

Determining the length of an Array in Java:
We can determine the current length of an array (at runtime) using the ".length" operator:
int [ ] A = new int [10];
System.out.println (A.length); // this expression evaluates to 10
A = new int [15];
System.out.println (A.length); // now it evaluates to 15

Copying an Array:
In Java, we can copy an array using the array copy function. Like the output function printing, array copy is provided in java.lang.System, so you must use the name System.arraycopy. The function has five parameters:

src: the source array (the array from which to copy)
scopes: the starting position in the source array
dst: the destination array (the array into which to copy)
dstPos: the starting position in the destination array
count: how many values to copy

Here is an example:

int [ ] A, B;
A = new int[10];
.............// code to put values into A
B = new int[5];
System.arraycopy(A, 0, B, 0, 5) // copies first 5 values from A to B
System.arraycopy(A, 9, B, 4, 1) // copies last value from A into last
//element of B

Note that the destination array must already exist i.e. new must already have been used to allocate space for that array, and it must be large enough to hold all copied values, otherwise you will get a runtime error. Furthermore, the source array must have enough values to copy i.e. the length of the source array must be at least srcPos+count.

For arrays of primitive types, the types of the source and destination arrays must be the same. For arrays of non-primitive types, System.arraycopy(A, j, B, k, n) is OK if the assignment B[0] = A[0] would be OK. The array copy function also works when the source and destination arrays are the same array. For example, you can use it to "shift" the values in an array:

into [ ] A = {0, 1, 2, 3, 4};
System.arraycopy(A, 0, A, 1, 4);

After executing the above code, A has the values: [0, 0, 1, 2, 3].

Multidimensional Arrays:
As in C++, Java arrays can be multidimensional. For example, a 2-dimensional array is an array of arrays. However, a two-dimensional array need not be rectangular. Each row can be of a different length. Here's an example:

int [ ][ ] A; // A is a two-dimensional array
A = new int[5][]; // A now has 5 rows, but no columns yet
A[0] = new int [1]; // A's first row has 1 column
A[1] = new int [2]; // A's second row has 2 columns
A[2] = new int [3]; // A's third row has 3 columns
A[3] = new int [5]; // A's fourth row has 5 columns
A[4] = new int [5]; // A's fifth row also has 5 columns