Different Ways To Declare And Initialize 2-D Array in Java
Last Updated :
13 Nov, 2024
An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is an array of arrays.
A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1x1 square boxes. You can similarly visualize a 2D array. In a 2D array, every element is associated with a row number and column number. Accessing any element of the 2D array is similar to accessing the record of an Excel File using both row number and column number. 2D arrays are useful while implementing a Tic-Tac-Toe game, Chess, or even storing the image pixels.
Example:
Java
import java.io.*;
class GFG {
public static void main(String[] args){
int n = 80, m = 5;
int[][] arr = new int[n][m];
// initializing the array elements using for loop
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = i + j;
}
}
// printing the first three rows of marks array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < m; j++)
System.out.printf(arr[i][j] + " ");
System.out.println();
}
}
}
Output0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
Note: We can use arr. length function to find the size of the rows (1st dimension), and arr[0].length function to find the size of the columns (2nd dimension).
Declaring 2-D array in Java
Any 2-dimensional array can be declared as follows:
Syntax:
// Method 1
data_type array_name[][];
// Method 2
data_type[][] array_name;
data_type: Since Java is a statically-typed language (i.e. it expects its variables to be declared before they can be assigned values). So, specifying the datatype decides the type of elements it will accept. e.g. to store integer values only, the data type will be declared as int.
array_name: It is the name that is given to the 2-D array. e.g. subjects, students, fruits, department, etc.
Note: We can write [ ][ ] after data_type or we can write [ ][ ] after array_name while declaring the 2D array.
Initialize 2-D array in Java
data_type[][] array_Name = new data_type[row][col];
The total elements in any 2D array will be equal to (row) * (col).
- row: The number of rows in an array
- col: The number of columns in an array.
When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted. Java compiler is smart enough to manipulate the size by checking the number of elements inside the columns.
// Incorrect Statement
int[][] arr = new int[][3];
// Correct Statement
int[][] arr = new int[2][];
You can access any element of a 2D array using row numbers and column numbers.

Different Ways to Declare and Initialize 2-D Array in Java
1. Inserting Elements while Initialization
In the code snippet below, we have not specified the number of rows and columns. However, the Java compiler is smart enough to manipulate the size by checking the number of elements inside the rows and columns.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Create a String Array
String[][] subjects = {
// Row 1
{ "Data Structures & Algorithms",
"Programming & Logic",
"Software Engineering",
"Theory of Computation" },
// Row 2
{ "Thermodynamics",
"Metallurgy",
"Machine Drawing",
"Fluid Mechanics" },
// Row 3
{ "Signals and Systems",
"Digital Electronics",
"Power Electronics" }
};
// Printing the Array Spoecific Index
System.out.println(subjects[0][0]);
System.out.println(subjects[1][3]);
System.out.println(subjects[2][1]);
}
}
OutputData Structures & Algorithms
Fluid Mechanics
Digital Electronics
2. Inserting Elements by Index
Moreover, we can initialize each element of the array separately. Look at the code snippet below:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args){
// Creating and Initialization of
// Array
int[][] scores = new int[2][2];
// Inserting elements in the specific index
scores[0][0] = 15;
scores[0][1] = 23;
scores[1][0] = 30;
scores[1][1] = 21;
// Printing the array elements individually
System.out.print(scores[0][0]+" ");
System.out.println(scores[0][1]);
System.out.print(scores[1][0]+" ");
System.out.println(scores[1][1]);
}
}
3. Inserting Elements in Jagged Array
There may be a certain scenario where you want every row to have a different number of columns. This type of array is called a Jagged Array.
Java
import java.io.*;
class GFG {
public static void main(String[] args){
// declaring a 2D array with 2 rows
int arr[][] = new int[2][];
// Jagged array with custom
// columns for each row
arr[0] = new int[2];
arr[1] = new int[4];
// Initializing the array
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = count++;
}
}
// Printing the values of 2D Jagged array
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.printf(arr[i][j] + " ");
System.out.println();
}
}
}
Similar Reads
How to Initialize an Array in Java?
An array in Java is a linear data structure, which is used to store multiple values of the same data type. In array each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java.
5 min read
Initialize an ArrayList in Java
ArrayList is a part of the collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though it may be slower than standard arrays, but can be helpful in programs where lots of manipulation in the array is needed.ArrayList inherits the AbstractList class and imp
4 min read
How to Declare an Array in Java?
In Java programming, arrays are one of the most essential data structures used to store multiple values of the same type in a single variable. Understanding how to declare an array in Java is very important. In this article, we will cover everything about array declaration, including the syntax, dif
3 min read
How to initialize an array in JavaScript ?
Initializing an array in JavaScript involves creating a variable and assigning it an array literal. The array items are enclosed in square bracket with comma-separated elements. These elements can be of any data type and can be omitted for an empty array.Initialize an Array using Array LiteralInitia
3 min read
Is there any difference between int[] a and int a[] in Java?
An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. In Java, Array can be declared in the following ways: One-Dimensional Arrays: The general form of a one-dimensional array declaration is type var-name[];ORtype[] v
6 min read
Difference between Array and String in Java
An array is a collection of similar type of elements that are stored in a contiguous memory location. Arrays can contain primitives(int, char, etc) as well as object(non-primitives) references of a class depending upon the definition of the array. In the case of primitive data type, the actual value
5 min read
How to Declare and Initialize 3x3 Matrix in PHP ?
PHP, a widely used scripting language, is primarily known for its web development capabilities. However, it also offers a robust set of features to perform various other programming tasks, including the creation and manipulation of matrices. A matrix is a two-dimensional array consisting of rows and
3 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created follo
3 min read
Difference between List and ArrayList in Java
A Collection is a group of individual objects represented as a single unit. Java provides a Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit This framework consists of the List Interface as well as the ArrayList class. In this article
4 min read
Difference Between one-dimensional and two-dimensional array
Array is a data structure that is used to store variables that are of similar data types at contiguous locations. The main advantage of the array is random access and cache friendliness. There are mainly three types of the array: One Dimensional (1D) ArrayTwo Dimension (2D) ArrayMultidimensional Arr
3 min read