Updated September 29, 2023
What are 2D Arrays in Java?
A 2D array, in simple terms, is an array of arrays in Java. Picture it as a table where each cell can hold a value. Unlike one-dimensional arrays, which can be considered a single row, a 2D array has rows and columns. It’s like a data universe organized into rows and columns for easy access and manipulation.
2D arrays in Java help to manage multidimensional data. They organize information into rows and columns, which makes them highly efficient for grids, matrices, gaming boards, and image processing. To work with 2D arrays effectively, knowledge of declaration, initialization, item access, operations, and performance optimization is required.
Table of Content
- What are 2D Arrays?
- Declaration and Initialization
- How to Create?
- How to Insert Elements?
- How to Remove Elements?
- How to Update Elements?
- Comparing 2D arrays with other data structures
- Accessing Elements
- Manipulating Elements
- Performing Operations on 2D Arrays
- Traversing 2D Arrays in Java
Declaration and Initialization of 2D Arrays
Declaring and initializing a 2D array in Java entails stating the Array’s type and dimensions and, if desired, giving the elements in the array values. Here is an explanation of the procedure and some examples of declaration and initialization techniques:
Syntax for declaring 2D arrays in Java
The following is the syntax for declaring a 2D array:
dataType[][] arrayName;
Here,
- dataType represents the data type of the elements you want to store in the Array, and
- arrayName is the name you choose for your 2D Array.
To initiate a fresh 2D array, utilize the “new” keyword together with the dimensions of the Array:
arrName = new dataType[rowSize][columnSize];
As an alternative, you may combine the declaration and initialization into a single statement:
dataType[][] arrName = new dataType[rowSize][columnSize];
Methods to initialize 2D arrays
Initializing 2D arrays in Java can be done using various methods tailored to your needs. Let’s explore different techniques for initializing 2D arrays with default or specific values.
Method 1: Default Initialization
In default initialization, all elements of the 2D Array are set to their default values based on their data types (e.g., 0 for numeric types, false for booleans, and null for reference types).
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
int[][] matrix = new int[3][3];
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]Method 2: Initializing with Specific Values
You can initialize a 2D array with specific values using nested loops, providing explicit values for each element.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
arrayName[i][j] = specificValue;
}
}
Example:
int[][] matrix = new int[3][3];
int value = 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = value;
value++;
}
}
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]Method 3: Initializing with Predefined Values
You can directly initialize a 2D array with predefined values without using nested loops.
Syntax:
dataType[][] arrayName = {
{val11, val12, val13, ...},
{val21, val22, val23, ...},
...
};
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]Method 4: Initializing with Array Constants
You can initialize a 2D array by directly assigning an array constant.
Syntax:
dataType[][] arrayName = {{val11, val12, ...}, {val21, val22, ...}, ...};
Example:
String[][] ticTacToeBoard = {
{"X", "O", "X"},
{"O", "X", "O"},
{"X", "O", "X"}
};
Output:
[[X, O, X], [O, X, O], [X, O, X]]Method 5: Using the Arrays.fill() method
The Arrays.fill() method can initialize the entire 2D Array with a specific value.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
for (dataType[] row : arrayName) {
Arrays.fill(row, specificValue);
}
Example:
int[][] matrix = new int[3][3];
int value = 7;
for (int[] row : matrix) {
Arrays.fill(row, value);
}
Output:
[[7, 7, 7], [7, 7, 7], [7, 7, 7]]Handling arrays with different row and column sizes
2D arrays in Java, also called jagged arrays, can include rows with different lengths. A separate 1D array is considered for each row.
You can assign different row sizes during initialization to initialize a jagged array.
When accessing or traversing a jagged array, you must account for varying row sizes using techniques such as nested loops or conditional checks to ensure you don’t go out of bounds for any row.
How to Create 2D Arrays in Java?
We will look at how to create 2 dimensional with the help of an example. Before that, let us look; we have two index values for a 2d array. One is for a row, and another is for a column.
- Row Size: Rows are the elements in an array that can be stored horizontally. For example, if the Row Size equals 4, the Array will be created with 4 rows.
- Column Size: Columns are the elements in an array that can be stored vertically. For example, if the Column Size equals 2, an array can have 2 Columns.
Example:
public class TwoDArray{
public static void main(String[] args) {
int[][] twoDimentional = {{12,27},{6,7},{24,3},{30,50}};
for(int i = 0 ; i < 4 ; i++){
for(int j = 0 ; j < 2; j++){
System.out.print(twoDimentional[i][j] + " ");
}
System.out.println();
}
}
}
Output:
How to Insert Elements of 2D Arrays in Java?
For inserting data in 2D arrays, we need two for loops because we are working with rows and columns here.
- Ask for an element position to insert the element in an array.
- Ask for value to insert
- Insert the value
- Increase the array counter
All the things mentioned above can be confusing. Let’s look at the program below, which illustrates how to take user input in a 2D array.
Please try out this program first. We will have a closer look at the below program.
Example
import java.util.Scanner;
public class InsArray{
public static void main(String[] args)
{
int[][] twodArray = new int[3][2]; // declared and created array object
Scanner s1 = new Scanner(System.in); //created Scanner object
System.out.println("Kindly input the values that need to be added");
for(int i = 0 ; i < 3 ; i++){
for(int j = 0 ; j < 2; j++)
{
twodArray[i][j] = s1.nextInt();
}
System.out.println();
}
System.out.println("You would get the following output:");
for(int i = 0 ; i < 3 ; i++){
for(int j = 0 ; j < 2; j++)
{
System.out.print(twodArray[i][j] + " " );
}
System.out.println();
}
}
}
Output:
In the above program, we have taken one array variable called twodArray. We just created the object of an array. We have not initialized this Array yet. For taking user input, we took the help of a scanner class in Java. We created the object of this class called s1. We created this object to use different methods specified in a class scanner.
Further, we used the nextInt() method in the scanner class to take input from the user at a particular location.
Here, we used nested for loops to loop over rows and columns. The first nesting set takes input from the user, which is nothing but inserting values in a 2-dimensional array. The second nesting of the for loop is to display user input on the screen in a matrix format.
This is an elementary program to understand. Suppose you are having trouble understanding nested for loop. Please learn first how for loop works in Java. Then try again.
How to Remove Elements?
- Now, it’s time to see if we need to remove some particular elements in the 2d Array. How can we achieve this?
- Now, this is the tricky question asked many times. But we must understand that we can’t delete an item in 2d arrays in Java. 2-dimensional arrays are nothing but an array of arrays. But there is a way to remove that element via replacing the places.
- With all these possibilities, there are also disadvantages over the Array, as we have a fixed size. Java also has a Java collection framework. This collection framework has an Array List, also the technique for working with different Java collections.
How to Update Elements of 2D Arrays in Java?
Till now, we have seen how to insert elements in a 2D array. Now, let’s check how we can update the existing 2D Array. To update elements in a 2-dimensional array, we must see which element we must update. If you are familiar with array concepts, you know we have an index number for each element; we can say the position in short. Let’s first jump on to the program, and later, we will see what we are doing with this.
Example
public class UpArray{
public static void main (String[] args)
{
String[][] twoDimentional = {{"11","13"},{"23","25"},{"33","36"},{"45","54"}};
System.out.println("Before updating an array: ");
printArray(twoDimentional);
twoDimentional[1][1] = "75";
twoDimentional[3][0] = "37";
System.out.println("After updating an array element: ");
printArray(twoDimentional);
}
private static void printArray(String[][] twoDimentional){
for(int i=0; i<twoDimentional.length; i++){
for(int j=0; j<twoDimentional[0].length; j++){
System.out.print(twoDimentional[i][j]);
}
System.out.println("");
}
}
}
Output:
In the above program, we have updated the value in the 2-dimensional Array. Our Array is named “two-dimensional.” We have values as {{“11″,”13”},{“23″,”25”},{“33″,”36”},{“45″,”54”}}. We know that a 2D array is an array of arrays. Here, we tried to update the value of the 4th Array. We took the value by its index position. In the Array, we know that the index starts at 0th. So, the array index would be 3. The first position in the Array means the 0th position. So it would be [3][0]. We assign a new value at the given position, i.e., [3][0]. That value is 37. You can see in the output above previously, 45 was there; after updating, 37 is there.
Comparing 2D arrays with other data structures
Accessing Elements in a 2D Array
When accessing an element in a 2D array using Java, it is essential to indicate both the row and column indexes. Keep in mind that the indices start counting from 0.
Syntax:
dataType element = arrayName[rowIndex][columnIndex];
Here, dataType represents the data type of the elements stored in the Array, arrayName is the name of your 2D Array, rowIndex is the desired row number, and columnIndex is the desired column number.
Example:
int[][] scores = {
{90, 85, 95},
{78, 88, 92},
{95, 90, 87},
{82, 79, 85},
{89, 92, 78}
};
// Accessing the element in the third row (index 2) and second column (index 1)
int element = scores[2][1];
System.out.println("Element at row 3, column 2: " + element);
Output:
Manipulating Elements in a 2D Array
Once you have accessed an element, you can manipulate its value by assigning a new value to it.
Syntax:
arrayName[rowIndex][columnIndex] = newValue;
Here, arrayName is the name of your 2D Array, rowIndex is the desired row number, columnIndex is the desired column number, and newValue is the data you wish to store in that cell.
Example:
int[][] scores = {
{90, 85, 95},
{78, 88, 92},
{95, 90, 87},
{82, 79, 85},
{89, 92, 78}
};
// Changing the score of the second student (index 1) in the first subject (index 0)
scores[1][0] = 80;
System.out.println("New score for student 2 in subject 1: " + scores[1][0]);
Output:
Traversing and Manipulating the Entire 2D Array
You can use nested loops to traverse the entire 2D Array and manipulate all elements.
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Traversing the 2D array and doubling each element
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] *= 2;
}
}
// Printing the updated 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Output:
Performing Operations on 2D Arrays
Applying arithmetic, logical, and mathematical operations on array elements
This involves performing mathematical operations such as addition, subtraction, multiplication, division, and logical operations on the elements of a 2D array. For example, the following code adds 30 to each element in the my_array Array:
for (int row = 0; row < my_array.length; row++) {
for (int column = 0; column < my_array[row].length; column++) {
my_array[row][column] += 30;
}
}
Implementing common algorithms for searching, sorting, and transforming 2D arrays
This involves implementing 2D arrays to algorithms like binary search, bubble sort, and matrix multiplication. To find the element with the value 50 in the my_array Array, for instance, the following code uses a binary search:
int element = 50;
int row = 0;
int column = my_array[0].length - 1;
while (row <= column) {
int middle = (row + column) / 2;
if (my_array[row][column] == element) {
break;
} else if (my_array[row][column] < element) {
row = middle + 1;
} else {
column = middle - 1;
}
}
Modifying and resizing 2D arrays dynamically
You can use specific code to modify the size of a 2D array or add/remove elements. For instance, the code below resizes the “my_array” array by adding 5 rows and 10 columns:
my_array = new int[5][10];
To add an element with the value 80 to the my_array Array at row 2, column 3, use the following code:
my_array[2][3] = 80;
Traversing 2D Arrays in Java
Traversing a 2D array involves systematically accessing and processing each element within the structure. Row-Major Order refers to traversing the elements row by row, from the top left corner to the bottom right, using nested loops with the outer loop iterating through the rows and the inner loop iterating through the columns. On the other hand, Column-Major Order involves traversing the elements column by column, from the top left corner to the bottom right, with the outer loop iterating through the columns and the inner loop iterating through the rows. The choice of traversal order can significantly impact the performance and efficiency of operations performed on the 2D Array.
Row-Major Order
In Row-Major Order, you traverse the 2D array row by row, moving from the top left corner to the bottom right corner. To achieve this captivating traversal, you employ nested loops. The rows are iterated through by the outer loop, while the inner loop iterates through the columns. Inside these loops, accessing elements follows the syntax:
matrix[i][j]
Here, i represents the row index, and j represents the column index. It’s like a journey across the rows, where you explore each column within the row before moving on to the next row.
Example:
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{21, 52, 23},
{64, 55, 67},
{47, 38, 99}
};
// Traversing in Row-Major Order
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Column-Major Order
In Column-Major Order, you embark on an adventure down each column, from the top left corner to the bottom right corner. Similarly, nested loops are used, but the roles are reversed. The outer loop now iterates through the columns, and the inner loop through the rows. Accessing elements follows this syntax:
matrix[j][i]
Here, j represents the column index, and i represents the row index. It’s as if you’re delving into each column, exploring its elements from top to bottom, before proceeding to the next column.
Example:
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Traversing in Column-Major Order
for (int j = 0; j < matrix[0].length; j++) {
for (int i = 0; i < matrix.length; i++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Conclusion
As we bid farewell to this enchanting exploration, we carry the understanding of 2D arrays as a valuable asset in our programming toolkit. With their versatility and efficiency, 2D arrays enable us to tackle complex problems and create elegant solutions in the realm of Java programming. Whether we are working with game development, image processing, data analysis, or any other domain, the knowledge of 2D arrays empowers us to unlock the full potential of multidimensional data structures.
FAQ’s
Q1. Can I change the size of an array after its declaration?
Ans: In the array realm of Java, arrays have a fixed size once declared. You cannot change it afterward.
Q2. Are arrays limited to primitive data types?
Ans: Oh, no! Arrays in Java can hold both primitive data types and objects, making them incredibly versatile.
Q3. Can I have an array with no elements in it?
Ans: Indeed! It is possible to declare an array without initializing it. This means that the Array will be empty until you add elements to it at a later time.
Q4. What happens if I access an element with an invalid index?
Ans: Beware the IndexOutOfBoundsException! Java guards its arrays diligently, and attempting to access an element with an invalid index will summon this exception.
Q5. Are arrays passed by value or reference in Java?
Ans: Arrays are passed by reference in Java, meaning any changes made to the Array in a method will affect the original Array.
Recommended Articles
We hope that this EDUCBA information on “2D Arrays in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information,