How to create a dynamic 2D array in Java

In this Java tutorial, we will show you how to create dynamic 2D array in Java. So this is the place where you are going to learn to create a multidimensional array in Java.

How to convert Byte Array to Image in java with easy example

We will cover up the following things here:

  • What is a two-dimensional array in Java
  • How to declare a two-dimensional array in Java
  • How to add elements to a 2d array in Java
  • And finally, create a 2d array in Java

How to create dynamic 2d array in Java

Before going to create a dynamic 2d array in Java we will explain what a 2d array is.

A 2d array in Java is an array which can hold the same type of data with a given single name as a concept of row and column cell.

Let’s understand this with an easy example.

int[][] a = new int[3][4];
Java 2d array - create dynamic 2d array in java

Java 2d array (image source:

Here we got a 2d array which can hold up to 12 elements in it.

Because we have declared the array size with 3 rows and 4 columns.

The syntax is like this:

int[][] a = new int[m][n];

Where is the number of rows and is the number of columns.

Initialize a 2d array in Java

int[][] my_array = {
      {5, 12, 73}, 
      {78, 45, 89, 11}, 

You can initialize a 2d array in this way.

Below I have provided a full example so that you can grab it easily:

class MyClass {
   public static void main(String args[]) {

      int[][] my_array = {
            {40, 41, 47}, 
            {42, -78, 7, 2}, 
     for (int i = 0; i < my_array.length; ++i) {
        for(int j = 0; j < my_array[i].length; ++j) {

Also read,

How to convert Java Array to JSON array?

Guess The Number Game Using Java with Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *