Two Dimensional Array in Java
An Array is a special fixed-length container that holds a collection of values having a common data type. A two-dimensional array is an array of arrays i.e., it's a collection of arrays in which elements are arranged in rows and columns (tabular format). We can access the elements using both the row index and column index
Introduction to 2D Array in Java
Data represented in tabular form (organized in rows and columns) is a very effective means of communicating many different types of information. For example, we use tables to represent our expenditures, daily schedules, etc. In short, we generally use a rectangular grid (a collection of rows and columns) to organize the data.
In Java, this tabular representation of data is implemented using a two-dimensional array. A two-dimensional array (or 2D array in Java) is a linear data structure that is used to store data in tabular format.
In Java, an array is a homogeneous collection of a fixed number of values stored in contiguous memory locations. The elements are of the same type (homogeneous data) and are linearly placed in memory such that each element is connected to its previous and next elements.
Java treats the two-dimensional array as a collection of multiple one-dimensional arrays. Hence, when we create a 2D array object, Java creates a simple one-dimensional array that references (points to) other one-dimensional arrays, which form the rows of the 2D array.
Hence, in Java, a two-dimensional array is a collection of pointers, where each pointer refers to a one-dimensional array that represents a particular row of the 2D array.
2D Array Declaration in Java
Since a 2D array in Java consists of rows and columns, we need two indices, one to refer to rows and the other to a particular column in that row. Hence, the syntax of declaring a two-dimensional array is similar to that of a one-dimensional array, with the exception of having two square brackets instead of one:
Here, the DataType describes the type of values that the array can store, while the ArrayName is the reference variable for the two-dimensional array object.
The above-described syntax only declares the array i.e., the memory is allocated for the array object but the values will be added later.
Create Two Dimensional Array in Java
In Java, everything including the array data structure is treated as objects. Hence, to create a two-dimensional array object, we need to use the new keyword as shown below:
Here, the new DataType[r][c] statement creates a two dimensional array object that contains r rows and c columns and elements of DataType type. This array object is referenced by the reference variable ArrayName.
Let's understand the creation of Java's two-dimensional array with an example:
Here, the reference variable a points to a two-dimensional array object that represents a integer matrix , the array object contains rows and columns, and can only store integer (int) values.
Note: When we create a 2D array object using the new keyword, the JVM (Java Virtual Machine) allocates the memory required for the two-dimensional array and initializes the memory spaces with the default values according to the data type of the array object. For example, in the case of the Integer array (int[][]), every element of the array is initialized with the default value of 0.
Java Two Dimensional Array of Primitive Type
Arrays are a collection of elements that have similar data types. Hence, we can create an array of primitive data types as well as objects. A 2D array is of a primitive data type in Java (let's say int) and is simply an array of Integer arrays.
We can declare a 2D array in Java for all the primitive Java data types in the following manner:
Java Two Dimensional Array of Objects
As discussed earlier, we can create an array of objects. A two-dimensional array of objects in Java is simply a collection of arrays of several reference variables. We can declare a 2D array of objects in the following manner:
This syntax declares a two-dimensional array having the name ArrayName that can store the objects of class ClassName in tabular form. These types of arrays that store objects as their elements are typically used while dealing with String data objects.
Accessing Two Dimensional Array Elements in Java
Arrays are stored in contiguous memory locations and use numeric indexing to reference these memory locations. Hence, we can directly access any element from an array using indexing. In the case of 2D array in Java, we use row and column indices to access a particular element from the matrix. It has the following syntax:
Here, the ArrayName[i][j] statement is used to access the element present at the intersection of ith row and jth column in the two dimensional array ArrayName. This element is then stored in the variable var.
Note :
- In Java, the index always starts from 0. Hence to access the element in nth row, we need to use (n-1) as the index.
- We can only access the elements of an array using positive integer as the index. We can't use negative indices to access any elements from an array in Java.
- If we pass an index that is greater than the size of the array (out of bounds index), the ArrayIndexOutOfBoundsException error will occur.
Example of Java Two Dimensional Array
Now, let's look at an example to completely understand 2D arrays in Java.
Consider a scenario where we wish to store the marks attained by 3 students in Maths, English, and Science Subjects. Here, we are storing a collection of marks (marks of English, Maths, and Science) for each student. Hence, we can use a table to represent and store student marks. In the Student Marks table, the rows will represent the marks of a particular student, and the columns will represent the subject in which the student attained those marks, as shown below:
This Student Marks table can be mapped into Java using 2D arrays. We can use a two-dimensional integer array to represent the tabular form for the marks of students. This can be implemented in the following manner:
Code:
Output:
Here, we are declaring an Integer array StudentMarks that represents a 3X3 matrix. Now, to assign the marks of each student, we are accessing the corresponding elements using indexing and then assigning the marks to that particular element.
For example, to store the marks attained by student 1 in English, we are accessing the 0th row (First student) and the 0th column (First subject i.e., English) and then replacing the default integer value of 0 with the marks of the student (StudentMarks[0][0] = 90).
Finally, we are using the built-in method deepToString() of the Arrays class to display the StudentMarks two-dimensional array.
Ways to Declare and Initialize Two Dimensional Array in Java
We can initialize and declare 2D arrays in various ways in Java. Let's look at each of these initialization methods in detail:
1. Declaring the 2D array with both dimensions
To declare a two-dimensional array using both dimensions, we just have to pass the number of rows and the number of columns of the matrix in the square brackets as shown below:
This syntax will declare a 2D Integer array having two rows and two columns.
2. Declaring a two-dimensional array with just one dimension
Since Java treats two-dimensional array as an array of arrays, we can declare a two-dimensional array using only one dimension which is the number of rows as the first dimension determines the number of array references.
This syntax will declare a two-dimensional Integer array having two rows and an undefined number of columns i.e., the array object a refers to an array that can further refer to two one-dimensional arrays.
3. Position of the square bracket
When declaring a two-dimensional array, the position of the square bracket in the declaration statement can cause unexpected results. Let's look at some examples to understand the common mistakes related to the position of square brackets:
In the above syntax, we are declaring two array objects, a and b, where the object a represents a one-dimensional integer array and the object b represents a two-dimensional integer array. Now,
This syntax can be used to create two-dimensional arrays in Java as the int[] indicates a one-dimensional Integer array and the a[] is an array object itself, thereby declaring an integer array of arrays which is, in turn, a two-dimensional array.
4. 2D array with the variable column length
Since Java allows us to declare 2D arrays by providing only one dimension, we can declare a two dimensional array with variable column length using the syntax given below:
The above syntax declares a two-dimensional integer array having 4 rows and the next four statements assign four one-dimensional arrays having lengths 1, 2, 3, and 4 respectively as the rows of the array. The output of this two-dimensional array is shown below:
These two-dimensional arrays with variable column lengths are typically used to represent a symmetric matrix, a square matrix containing duplicate elements alongside the main diagonal.
5. Declaring and initializing a heterogeneous 2D array
Since we can create a two-dimensional array of Objects, we can make use of this feature and Java's built-in Object class to create a two-dimensional heterogeneous array using the below-described syntax:
This syntax declares a two-dimensional array having 3 rows and variable-length columns. The above syntax creates a two-dimensional array that looks like this:
Here, note that we are not using primitive data types like int, double, and char to declare the one-dimensional arrays. Instead, we are using their wrapper classes Integer, Character, and Double. This is because the two-dimensional array can only contain similar data type elements, which are objects of the built-in class Object.
Conclusion
- In this article, we have seen the 2D arrays in Java and their uses.
- Then, we have seen various ways the two-dimensional arrays can be declared in Java.
- We have also seen how Java treats the two-dimensional arrays and how the JVM allocates the memory to implement the two-dimensional arrays.
- We have also noticed that we can use indexing to access and change the elements of the two-dimensional arrays. Finally, we have seen the various ways in which two-dimensional arrays can be initialized and declared in Java and some common mistakes in declaration statements.