Arrays - Part 2
Introduction
We learned Arrays and executed some simple operations like accessing and modifying them in the last unit.
In this unit, we will learn how to execute some more operations like concatenating two arrays and locating subarrays. We will learn about Multi-dimensional arrays as well.
1. Array Concatenation
The process of merging two arrays is referred to as Array Concatenation. The System class has a method called arraycopy() in Java that is used for concatenating two arrays.
Syntax
System.arraycopy(array1, array1StartPosition, array2, array2StartPosition, noOfElements);
Here,
array1: is the name of the source array.
array1StartPosition: indicates from which position in the source array the elements need to be copied.
array2: is the name of the destination array
array2StartPosition: indicates to which position in the destination array the elements need to be added to.
noOfElements: is the number of array elements to be copied.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr1 = {12, 4, 5, 2, 5};
int[] arr2 = {6, 10,11,6};
int arr1Len = arr1.length; // 5
int arr2Len = arr2.length; // 4
int[] concatenatedArr = new int[arr1Len + arr2Len]; // new int[9]
System.arraycopy(arr1, 0, concatenatedArr, 0, arr1Len);
System.out.println(Arrays.toString(concatenatedArr));
// Concatenated array after array1 elements is copied to it.
System.arraycopy(arr2, 0, concatenatedArr, arr1Len, arr2Len);
System.out.println(Arrays.toString(concatenatedArr));
}
}
Output:
[12, 4, 5, 2, 5, 0, 0, 0, 0]
[12, 4, 5, 2, 5, 6, 10, 11, 6]
In the above code,
concatenatedArr has space for holding 9 integer values.
arraycopy(arr1, 0, concatenatedArr, 0, 5) method instructs the program to copy 5 elements of arr1 from index 0 to concatenatedArr from index 0.
The initial output of the code is the concatenatedArr after copying elements of arr1 into it.
arraycopy(arr2, 0, concatenatedArr, 5, 4) method instructs the program to copy 4 elements of array2 beginning from index 0 into concatenatedArr beginning from index 5.
The second output of the code is the concatenatedArr after copying elements of arr2 into it.
2. Array Slicing
Array slicing is a technique to get a subarray of an array.
We can obtain the subarray from an array through Arrays.copyOfRange() method.
Syntax
Arrays.copyOfRange(arrayName, startIndex, endIndex);
Here,
arrayName is the array name
The subarray begins from startIndex and ends at endIndex - 1
endIndex is not part of the subarray.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] originalArr = { 1, 2, 3, 4, 5 };
int startIndex = 2;
int endIndex = 4;
// copying the subarray from the original array to sliced array
int[] slicedArr = Arrays.copyOfRange(originalArr, startIndex, endIndex);
System.out.println(Arrays.toString(slicedArr));
}
}
Output:
[3, 4]
3. Multi-dimensional Array
A multi-dimensional array is an array of arrays. It is just like Python's list of lists.
We can make N Dimensional arrays such as 2D, 3D, etc.
In the last unit, we studied one-dimensional arrays.
Let us now see the two-dimensional (2D) array.
Two-dimensional Array
A two-dimensional array is the most basic type of multidimensional array. A two-dimensional array is an array of arrays. That is, a two-dimensional array is an array of one-dimensional arrays.
A two-dimensional array can be thought of as a matrix, which can be depicted as a list of rows and columns.
{
{12, 24, 36},
{15, 30, 45},
{16, 32, 48}
}
Here,
this two-dimensional array is an array of 3 one-dimensional arrays
rows = number of one-dimensional arrays = 3
columns = number of elements in each row = 3
number of elements in two-dimensional array = (number of rows * number of columns) = 3 * 3 = 9
We know index in an array begins from 0. Therefore, indexing of rows and columns also begins from 0.
The array {12, 24, 36} is the 1st row of the two-dimensional array, for this complete row every element has its row index as 0 and the column index will lie from 0 to 2.
12 is stored at the 0th row and 0th column of the array
24 is stored at the 0th row and 1st column of the array and so on for further elements for this row.
The array {15, 30, 45} is the 2nd row of a two-dimensional array, for this entire row all elements will have their row index as 1 and the column index will range from 0 to 2.
15 is located at the 1st row and 0th column of the array
30 is located at the 1st row and 1st column of the array and similarly for other elements for this row.
Two-dimensional Array Declaration
The declaration syntax of a two-dimensional array is:
Syntax
dataType[][] arrayName;
It is almost similar to the one-dimensional array. The [][] following the dataType, makes it distinct from the one-dimensional array and normal variable declarations.
The number of square braces ([]) shows the dimensions. For instance, three-dimensional (3D) array is declared as dataType[][][] arrayName
Code
class Main {
public static void main(String[] args) {
int[][] arr; // declare a two-dimensional array
}
}
It is a two-dimensional array where elements can be stored of type int.
4. Initialization & Declaration of Two-dimensional Array
We can declare, initialize and create a two-dimensional array using array literals.
The below is the syntax for creating a two-dimensional array by using array literals:
Syntax
dataType[][] arrayName = { {value00, value01,.}, {value10, value11,.}, {value20, value21,.},.};
Here,
value00: is the value which will be stored at the 0th row and 0th column of the array arr.
value01: is the value which will be stored at the 0th row and 1st column of the array arr and so on.
Example:
Code
class Main {
public static void main(String[] args) {
int[][] arr = {
{45, 42},
{11, 34},
{56, 79}
};
}
}
Output:
In the above code,
The number of rows is 3
The number of columns is 2
0th row and 0th column of array arr have the value 45.
0th row and 1st column of array arr have the value 42.
1st row and 0th column of array arr have the value 11 and so on.
5. Accessing Two-dimensional Array Elements
We access a specific element from a two-dimensional array using row and column indices.
Syntax
arrayName[rowNo][colNo];
Code:
class Main {
public static void main(String[] args) {
int[][] arr = {{12, 4, 5}, {16, 18, 20}};
System.out.println(arr[0][0]);
System.out.println(arr[1][1]);
System.out.println(arr[1][2]);
}
}
Output:
12
18
20
6. Printing a Two-dimensional Array
Print a two-dimensional array or a multi-dimensional array using Arrays.deepToString() method.
Code
import java.util.Arrays;
class Main
public static void main(String[] args) {
int[][] arr = {
{12, 4, 5},
{16, 18, 20}
};
System.out.println(Arrays.deepToString(arr));
}
}
Output:
[[12, 4, 5], [16, 18, 20]]
7. Declaration of a Two-dimensional Array using new Keyword
We can also declare the two-dimensional array with the help of a new keyword. With this technique, we can declare a two-dimensional array of the desired number of columns and rows and then assign the values.
The following is the syntax to declare an array with a new keyword:
Syntax
dataType[][] arrayName = new dataType[rows][columns];
Here,
arrayName: identifier for the two-dimensional array.
rows: denotes the number of rows.
columns: defines the number of columns.
Example:
Let us declare a two-dimensional array named arr:
Code
class Main {
public static void main(String[] args) {
int[][] arr; // declaring an array
arr = new int[2][2]; // memory allocation for arr
}
}
In the code above, the declaration arr = new int[2][2] reserves space for holding 2*2 = 4 int values.
After making a memory for the two-dimensional array, each element gets a default value of 0 since the array is of type int.
Assignment of Values
Let's go ahead and assign the values to the two-dimensional array created through the new keyword.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[][] arr; // declaring an array
arr = new int[2][2]; // allocating memory for arr
// assigning values to first row
arr[0][0] = 12;
arr[0][1] = 46;
// assigning values to second row
arr[1][0] = 61;
arr[1][1] = 90;
System.out.println(Arrays.deepToString(arr));
}
}
Output:
[[12, 46], [61, 90]]
8. Iterating Over a Two-dimensional Array
We can iterate over a two-dimensional array using nested loops.
Nested for Loop
We can use the nested for loop to iterate over a two-dimensional array.
Code
class Main {
public static void main(String[] args) {
int[][] arr =
{12, 45, 54},
{16, 18, 20},
{23, 78, 53}
};
int rows = arr.length;
int cols = arr[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.println("arr[" + i +"][\" + j + \"]: " + arr[i][j]);
}
}
}
}
Output:
arr[0][0]: 12
arr[0][1]: 45
arr[0][2]: 54
arr[1][0]: 16
arr[1][1]: 18
arr[1][2]: 20
arr[2][0]: 23
arr[2][1]: 78
arr[2][2]: 53
In the above code,
The array arr has 3 rows and each row has 3 elements. Therefore, rows = 3 and cols = 3.
The outer for loop runs from i = 0 to i = 2, this loop takes care of the row number.
The inner for loop runs from j = 0 to j = 2, this loop takes care of the column number.
At i = 0, and
j = 0, System.out.println(arr[0][0]) will print the 0th row and 0th column value of the array arr.
In the same way, it executes up to j = 2.
j = 3, the test condition in the inner loop is not satisfied and the control reaches the outer loop now.
In the same way, the respective row values will be printed for i = 1, and 1 = 2
9. Read & Store User Inputs in a Two-dimensional Array
In the last unit, we have learned to read and keep the user inputs in a one-dimensional array. Just like the one-dimensional array, first, we must declare an array (two-dimensional array) to keep the user inputs.
We employed for loop to read the user inputs in a one-dimensional array. For a two-dimensional array, we must employ nested for loops.
We have to obtain the number of rows and columns needed to form the two-dimensional array. For this purpose, let's assume that the first two numbers specify the rows and columns, and then there are the actual values to be stored.
Code
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int rows = input.nextInt(); // reads the number of rows.
int cols = input.nextInt(); // reads the number of columns.
int[][] arr = new int[rows][cols]; // creating a two-dimensional arrray
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = input.nextInt(); // reading and storing user inputs in array
}
}
System.out.println(Arrays.deepToString(arr));
input.close();
}
}
Input 1:
2 2
16 64
32 128
Input 2:
2
2
16
64
32
128
Output:
[[16, 64], [32, 128]]
The code above serves equally for Input 1 and Input 2.
Summary
Array Concatenation,
We can concatenate arrays using the System.arraycopy() method.
Array Slicing,
We can employ the Arrays.copyOfRange() method to slice arrays.
Multi-dimensional arrays,
A multi-dimensional array is an array of arrays.
A two-dimensional array will have rows and columns.
We can employ the Arrays.deepToString() method to print elements in the multi-dimensional arrays.
We can iterate over a multi-dimensional array by employing nested loops.