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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read