How to declare and Initialize two dimensional Array in Java with Example

An array of more than one dimension is known as a multi-dimensional array. Two of the most common examples of multi-dimensional arrays are two and three-dimensional arrays, known as 2D and 3D arrays, anything above is rare. I have never seen 4-dimensional arrays, even 3D arrays are not that common. Now the question comes when to use a multi-dimensional array? Any real-life example? Well, 2D arrays are very common on platform games like Super Mario Bros to represent screen or terrain; 2D arrays can also be used to represent structures like a spreadsheet, or to draw board games like Chess, which requires an 8x8 board, Checkers and  Tic-Tac-Toe, which requires 3 rows and 3 columns.

Another popular application of multi-dimensional arrays is in matrix manipulation. For example to represent a 3x3 matrix you need a two-dimensional array of 3 one-dimensional arrays each containing 3 elements.

Similarly to represent 3x2 matrices you need 2 two-dimensional arrays of a one-dimensional array of length 3. In other words, each row in a two-dimensional array is a one-dimensional array.  Java truly doesn't support a multi-dimensional array but allows you to create and use an array of any number of dimensional.

A two-dimensional array is actually an array of one-dimensional array. This is unlike languages like C or FORTRAN, which allows Java arrays to have rows of varying lengths i.e. a multidimensional array can have 2 columns in one row and 3 columns in a second.

Similar to the one-dimensional array, the length of the two-dimensional array is also fixed. You can not change the length of an array, I mean, the number of rows and columns will remain fixed. 

A 2x2 array can hold a total of 4 elements and they can be accessed using row and column index like a[0][0] will give you elements in the first row and first column, similarly a[1][1] will give you elements from 2nd row and 2nd column. Just like a normal array, the index starts at 0 and finishes at length -1.

Though, if you are not familiar with an essential data structure like an array and linked list, then I suggest you first go through a comprehensive fundamental course like Data Structures and Algorithms: Deep Dive Using Java on Udemy. It's a very important topic for any programmer be it a core Java developer or Java web developer and you just can not afford to ignore this.

How to Declare 2 Dimensional Array in Java? Example

If you know how to create a one-dimensional array and the fact that multi-dimensional arrays are just an array of the array in Java, then creating a 2-dimensional array is very easy. Instead of one bracket, you will use two e.g. int[][] is a two-dimensional integer array. You can define a 2D array in Java as follows :

int[][] multiples = new int[4][2];     // 2D integer array with 4 rows 
                                          and 2 columns
String[][] cities = new String[3][3];  // 2D String array with 3 rows 
                                          and 3 columns

By the way, when you initially declare a two-dimensional array, you must remember to specify the first dimension, for example following array declaration is illegal in Java.

 int[][] wrong = new int[][]; // not OK, you must specify 1st dimension
 int[][] right = new int[2][]; // OK

The first expression will throw the "Variable must provide either dimension expressions or an array initializer" error at compile time. On the other hand, the second dimension is optional, and even if you don't specify compiler will not complain, as shown below :

String[][] myArray = new String[5][]; // OK
String[][] yourArray = new String[5][4]; // OK

This is possible because a two-dimensional array in Java is nothing but an array of a one-dimensional array, because of this, you can also create a two-dimensional array where individual one-dimensional arrays have different lengths, as seen in the following example.

class TwoDimensionalArray {

    public static void main(String[] args) {
        String[][] salutation = {
            {"Mr. ", "Mrs. ", "Ms. "},

        // Mr. Kumar
        System.out.println(salutation[0][0] + salutation[1][0]);

        // Mrs. Kumar
        System.out.println(salutation[0][1] + salutation[1][0]);

The output from this program is:

Mr. Kumar
Mrs. Kumar

In this example, you can see that salutation is a 2D array but its first row has 3 elements while the second row has just one element.

You can access elements of a two-dimensional array either by using both indexes or just one index. For example salutation[0][1] represents a Single String in Java, while salutation[0]  represents a one-dimensional array ( a single row in the 2-dimensional array). You can further see Algorithms and Data Structures - Part 1 and 2 courses on Pluralsight to learn more about it.

How to Initialize Two Dimensional Array in Java? Example

So far we have just declared and created the array, we haven't initialized them. This means all elements of the array have their default values e.g. zero for an array of integral values like byte, short, char, and int,  0.0 for floating-point arrays like float and double, false for boolean arrays, and null for an array of reference type like String array elements.

You can verify this by accessing the first element of a two-dimensional array as multiples[0][0], which will print zero, as shown below:

           boolean[][] booleans = new boolean[2][2];
           System.out.println("booleans[0][0] : " + booleans[0][0]);
           byte[][] bytes = new byte[2][2];
           System.out.println("bytes[0][0] : " + bytes[0][0]);
           char[][] chars = new char[1][1];
           System.out.println("chars[0][0] : " +  (int)chars[0][0]);
           short[][] shorts = new short[2][2];
           System.out.println("short[0][0] : " + shorts[0][0]);
           int[][] ints = new int[3][2];
           System.out.println("ints[0][0] : " + ints[0][0]);
           long[][] longs = new long[2][2];
           System.out.println("longs[0][0] : " + longs[0][0]);
           float[][] floats = new float[1][2];
           System.out.println("floats[0][0] : " + floats[0][0]);
           double[][] doubles = new double[2][2];
           System.out.println("doubles[0][0] : " + doubles[0][0]);
           Object[][] objects = new Object[2][2];
           System.out.println("objects[0][0] : " + objects[0][0]);

           booleans[0][0] : false
           bytes[0][0] : 0
           chars[0][0] : 0
           short[0][0] : 0
           ints[0][0] : 0
           longs[0][0] : 0
           floats[0][0] : 0.0
           doubles[0][0] : 0.0
           objects[0][0] : null
You can see the default values of different types of primitive arrays here. Character array is a bit tricky because if you print 0 as a character it will print a null character and that's why I have used its integer value by casting to int.

Now there are two ways to initialize a two-dimensional array in Java, either by using an array literal at the time of creation or by using nested for loop and going through each element.

In the next example, we will learn how to loop through a two-dimensional array, initialize each element and how to print a two-dimensional array in Java:

       // initializing two dimensional array as literal
        String[][] names = { 
                            {"Sam", "Smith"},
                            {"Robert", "Delgro"},
                            {"James", "Gosling"},

        // how to initialize two dimensional array in Java
        // using for loop
        int[][] board = new int[3][3];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = i + j;

In the first example, we have created and initialized a String array using an array literal, while in the second example we have created a two-dimensional array board, and later initialized it by looping through the array. You can further see Object-Oriented Java Programming: Data Structures and Beyond Specialization on Coursera to learn more about how to use an array and other data structures in real-world projects.

How to Loop and Print 2D array in Java? Example

If you want to access each element of a two-dimensional array, then you need to iterate through the two-dimensional array using two for loops. Why? because you need two indexes to access an individual element from the 2D array. You can either use advanced for each loop or classic for loop with a counter.

The second one is more powerful as it provides an explicit counter which can be used as indexes. To print the contents of a two-dimensional array, you can either use this method or can use Arrays.deepToString() method, which will return a String version of all elements of a 2D array, as shown in the following example.

import java.util.Arrays;

 * Java Program to initialize and print two dimensional array in Java.
 * @author WINDOWS 8
class Basics {

    public static void main(String args[]) {
        // initializing two dimensional array as literal
        String[][] names = { 
                            {"John", "Smith"},
                            {"Javin", "Paul"},
                            {"James", "Gosling"},

        // how to initialize two dimensional array in Java
        // using for loop
        int[][] board = new int[3][3];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = i + j;

        // now let's print a two dimensional array in Java
        for (int[] a : board) {
            for (int i : a) {
                System.out.print(i + "\t");
        // printing 2D array using Arrays.deepToString() method
        System.out.println("another way to print 2D arrays");


0   1   2   

1   2   3   

2   3   4   

another way to print 2D arrays
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]

This was an important trick to learn while working with Array in Java. If you want to learn more such tricks, you can also join the Data Structures and Algorithms Specialization on Coursera. It's a free course to audit but you need need to pay if you need certification. This course will teach you algorithms through programming and help you to advance your software engineering or data science career

Important Points about Multi-dimensional Array in Java

1)  Java doesn't support a multi-dimensional array in the true sense. In a true two-dimensional array, all the elements of the array occupy a contiguous block of memory, but that's not true in Java. Instead, a multi-dimensional array is an array of array.

For example, a two-dimensional array in Java is simply an array of a one-dimensional array, I mean String[][] is an array of String[] or "array of array of strings".

This diagram shows how exactly two-dimensional arrays are stored in Java :

How two dimensional array are stored in Java

2) Because of the above reason, the second dimension in an array is optional in Java. You can create a two-dimensional array without specifying both dimensions like int[4][] is a valid array declaration. It also allows you to create a multi-dimensional array whose rows can vary in length, as we have seen in our second example.

3) While creating two dimensional or three-dimensional array in Java, the first dimension is a must, without that compile will throw an error e.g. int[][3] is Not Ok but int[3][] is Ok.

4) A two-dimensional array is a very useful data structure in game programming. You can use it on tile-based games like Super Mario Bros to draw terrain, background, and other objects, on games like Tetris to represent the playing areas.

A 2D array is also very useful in matrix manipulation. You can use a 2D array to represent any matrix and perform addition, multiplication, and other operations. A 2D array can also be used to represent any object in plain using X and Y coordinates.

Similarly, 3D arrays can be used to represent things in three-dimensional space using X, Y, and Z coordinates. Some of the popular examples of two-dimensional arrays are chess board, checkers board, and other board games which have slots. You can view the chessboard as an array of 8 rows and 8 columns.

5) There are multiple ways to define and initialize a multidimensional array in Java, you can either initialize them using in the line of declaration or sometime later using a nested for loop. You will need as many for a loop as many dimensions of the array you have. For example to explicitly initialize a three-dimensional array you will need three nested for loops. On the other hand, to initialize a 2D array, you just need two nested loops.

6) In a two dimensional array like int[][] numbers = new int[3][2], there are three rows and two columns. You can also visualize it like a 3 integer arrays of length 2. You can find the number of rows using numbers.length and number of columns using numbers[0].length expression, as shown in the below example. This is also very useful while iterating over a two-dimensional array in Java.
int[][] primes = new int[3][2];
int rows = primes.length; // 3
int cols = primes[0].length; // 2
System.out.printf("int[3][2] has %s rows and %d columns %n", rows, cols);
Output : int[3][2] has 3 rows and 2 columns

That's all about multi-dimensional array in Java. It is one of the useful data structures, especially to represent two-dimensional things like a matrix. It is also very useful to build tile-based games. By the way,  It's worth remembering that Java doesn't support true multi-dimensional arrays, instead, they are represented as "array of array".

Do you want to learn more about the array data structure? The most important Data structure for a programmer - If Yes, here are a couple of more articles which you can explore to learn about Array better:
  • 20+ String Coding Problems from Interviews (questions)
  • How to create an array from ArrayList of String in Java (tutorial)
  • 100+ Data Structure Problems from Interviews (questions)
  • Top 30 Array-based Coding Problems from Interviews (questions)
  • How to remove duplicates from an unsorted array in Java? (solution)
  • 10 Data Structure Courses to Crack Programming Interviews (courses)
  • How to find all pairs whose sum is equal to a given number in an array? (solution)
  • How to reverse an array in place in Java? (solution)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 10 Free Data Structure and Algorithm Courses for Beginners (courses)
  • Top 20 Searching and Sorting Interview Questions (questions)
  • How to make a binary search tree in Java? (solution)
  • 10 (Free) Online Courses to Learn Data Structure and Algorithms in Java (courses)
  • 50+ Data Structure and Algorithms Interview Questions (questions)

Thanks for reading this article so far. If you like this two-dimensional array tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses from Udemy and Coursera to start with.


  1. Can you create 2 dimension array even when each sub array are not of equal lenght?

    1. Ye you can. A 2D array is an array of arrays. Those arrays don't have to be of the same length.

    2. You can declare 2 dimensional array where each sub array is of different length because its not mandatory to specify length of second dimension while declaring 2D array in Java. This way you can initialize 2D array with different length sub array as shown below :

      String[][] squares = new String[3][];

      squares[0] = new String[10];
      squares[1] = new String[20];
      squares[2] = new String[30];

      You can see that our 2 dimensional array contains 3 sub array each with different length 10, 20 and 30.

  2. Is it possible to create hetrogenous two dimensional array in Java? Since 2D array is array of array, can I have array containing String[], Integer [] and Object[] as sub array?

    1. Yes, its possible but only if you declare your 2D array as Object[][], which is array of Object array, as shown below :

      Object[][] squares = new String[3][];

      squares[0] = new Integer[]{1, 3, 4,};
      squares[1] = new String[]{"A", "b"};
      squares[2] = new Float[]{1.0f, 2.0f};

      You can see that our Object[][] is heterogeneous, it contains String[], Integer[] and Float[] all in one Object[].

    2. so how can we get data? square[0][1] = 3?

    3. so how can we get an element? square[0][1] = 3?

    4. so how we can get all above data like string,integer,and float??

  3. how can we understand the flow of [2][3] matrices by taking for loop.could you please explain the flow

    1. Hello Sameera, Similar to above example you can write nested loop, first will go through each row and second will go through each column. This way you will access all elements of matrix e.g. [0][0] first row first column, [0[[1] first row second column and [0][2] first row third column.

  4. How to code this using two dimensional array in java? This is the output.
    Enter 9 values:
    1 2 3
    4 5 6
    7 8 9
    Total: 45

    1. import java.util.Scanner;

      public class JunesBautista
      public static void main(String args[])
      int k=0;
      int row, col, i, j;
      int arr[][] = new int[10][10];
      Scanner scan = new Scanner(;

      System.out.print("Enter Number of Row for Array (max 10) : ");
      row = scan.nextInt();
      System.out.print("Enter Number of Column for Array (max 10) : ");
      col = scan.nextInt();

      System.out.print("Enter " +(row*col)+ " Values : \n");
      for(i=0; i<row; i++)
      for(j=0; j<col; j++)
      arr[i][j] = scan.nextInt();

      for(i=0; i<row; i++)
      for(j=0; j<col; j++)
      System.out.print(arr[i][j]+ " ");


      System.out.println("Total is:" +k);



    2. 1 2 3
      8 9 4
      7 6 5
      i wont print like that plz help me

    3. please help me..

      Write a complete Java program in the text field below that will require the user to input integer values in a 2 dimensional array defined by a size of 10 x 10. The program should:

      initialize the array to 0
      input values
      print the contents of the array in a matrix format.

  5. ellow
    can you code this..

    this is the output

    Please enter the grade of student 1
    Please enter the grade of student 2

    "up to 10 student"

    Q1 Q2 Q3
    Student 1 81 91 91
    Student 98 90 98

    this code are using Scanner and multi dimensional array
    please help me..

  6. char[] arr = ['0','1','~','n','a','m','e','1','~','h','y','d','&','0','2','~','n','a','m','e','2','~','p','u','n','e'];

    It has sets of information like id, name, place seperated by a special char. Each set is again seperated by another special char.
    Iterate over the arrays and display the information in the following format. The solution to this problems should be generic.

    id : 01
    name : name1
    place : hyd

    id : 02
    name : name2
    place : pune

    Note : Do not use any JAVA API to get the output. Use only loops and conditional statements.

  7. how can i use 2d array in writing a code for login & registration details using only basic java knowledge?

  8. can you codes this problem sir ? :)
    Problem A: Single Dimensional Array
    Prompt the user to enter array length. The Program will now store Double typed numbers and will get the average.

    Enter array size: 10
    Enter 10 double – typed numbers:
    80 99 85 100 77 78 96 100 85 100

    The Average of stored numbers is 90.0
    Problem B: Two-Dimensional Array
    Ask your user to enter table dimensions. The user will save characters according to the size of the table. Display table items and create search item query, asking your user to enter table address.

    Enter number of rows: 3
    Enter number of columns: 2
    Enter 6 characters:
    A J K L D O

    Table items are:
    A J
    K L
    D O

    Enter Items to search: L
    L is at row 1 column 1
    Problem C: Class Vector
    Sample Run:

    Welcome to My Members List
    [ 1 ] Add New Names
    [ 2 ] Remove Names
    [ 3 ] View Names
    [ 4 ] Exit

    Select Transaction: 1
    Enter number of items to add: 3
    Enter 3 names separated by space: Jessie Justin Darius
    Items added! Your updated list are (Jessie, Justin, Darius)

    Select Transaction: 2
    Enter index number of item to remove: 1
    Are you sure you want to remove this item? [Y / N]: Y
    Item removed successfully. Your updated list are (Jessie, Darius)

    Select Transaction: 3
    Your String list are as follows:
    (Jessie, Darius)

  9. how to print matrix representation in a webpage using jsp


  10. import java.util.Arrays;
    import java.util.Scanner;
    public class MatrixDiagnal
    public static void main (String args[])
    int i,j,sum1=0,sum2=0,sum3=0,sum4=0,sum5=0;
    int x[][] = new int [3][3];
    System.out.println("Type the digit:");
    Scanner ob=new Scanner(;

  11. 1 2 3
    6 5 4
    7 8 9
    i wont print like that please healp me

    1. //ary is the 2d array, indents are messed up
      for (int i = 0; i < ary.length; i++) {
      for (int j = 0; j < ary[i].length; j++)
      System.out.print(ary[i][j] + " ");

    2. int[][] a=new int[3][3];
      int count=1;
      for(int i=0;i<a.length;i++){
      for(int j=0;j<a[i].length;j++){
      if(i==1 && j==0){
      }else if(i==1 && j==2){

      for(int[] in:a){
      for(int ia: in){
      System.out.print(ia+" ");

  12. Branch1 Branch2 Branch3 Branch4 Branch5 Total Average(per Parts)
    625 226 354 158 844 2207 441.4
    225 154 251 331 154 1145 229
    224 355 100 84 225 988 197.6
    331 25 62 544 654 1616 469.2
    588 664 354 555 185 2346 469.2

    How is this guys?

  13. How to initialize the array of type
    int rows=3;
    int s[] = new int[rows][];

    Now how to initialize it?

  14. How to initialize a global array in which number of columns varies?

    int a[][] = new int[3][];

    How to initialize it if I don't know the number of columns at present?

    1. Hello @Akshay, you can do this with two dimensional array where just first index is mandatory but with one dimensional array you must specify number of items. You can see my post 6 ways to declare two dimensional array in Java for more details.

  15. How do you fill a 2-D Array?

    1. Hello @Anonymous, you can do this by using a 2 dimensional for loop, first loop will fill the rows and second will fill the columns.

  16. Coordinate is (4,5) s = 6 I want to print like that:

  17. Help please
    The function takes two parameters: width
    and height and returns with value populate in decreasing order. Consider the
    following example:
    width 4 and height 2
    result would be

    [8 7 6 5],
    [4 3 2 1],

  18. Any suggestions on how to go about populating a 2D array with the values from another array. For example I am working on a Flea Circus program for my final project of my java class. There is a 30 by 30 grid that we need to populate with 900 fleas. The instructor suggested we use a 2D array with 900 rows for the fleas and another 2D array for the 30 by 30 grid. I am struggling in how to populate the grid array with the flea array.

    1. I think there is a disconnect, 2D array with 900 rows doesn't make sense, 2D array for the 30by30 grid does. what does flea means here, an object?

  19. How to display the common elements of two String array in multi dimensional array

  20. Outline: In this project, you are expected to write a basic abbreviation data base program. The program will read several abbreviations. Then, the program will check if the same abbreviation already exists in the data base. If not, it will add this new abbreviation to the correct place in the database.
    The input will be given as a series of String values until the String value of “STOP” is given.
    Example input:
    The abbreviation data base will be composed of a 2D String array with 7 columns and 18 rows. Abbreviations starting with „A‟ to „C‟ will be kept in the first column, abbreviations starting with „D‟ to „F‟ will be kept in the second column, and so on as seen in the figure below. For the input above, the 2D String array will look this:
    A - C
    While inserting a new abbreviation to the data base, the program will check if the same abbreviation exists in the data base or not. If it does, the program will NOT add this abbreviation to the data base a second time.
    After checking over all the input, the program will write the data base to the screen as seen below:
    D – F:
    G– J: IOT JIT
    K – N: NLP
    O – R: PTT
    S – V: ST VOY
    W – Z: ZEX
     The abbreviations as Strings
     The data base as 7 rows of output as seen above in the example.
    NOTE: For each column there can be no more than 18 abbreviations. You do NOT need to check this in the input.
    NOTE: Abbreviations will ALWAYS be given as capital letters and they will ALWAYS start with an English letter. You
    need to check this in the input.
    HINT: For checking if a given String exists in the data base, it would be a good idea to write a method like
    (doesExistInDB). Using such a method will reduce a lot of code repetition.
    HINT: Do not forget to use the “.equals” method for comparing two Strings with each other.
    HINT: If you cannot make the “checking if the String exists in the data base” you might get PARTIAL points. So, submit
    your project.
    Sample Input/Outputs:
    Input Output
    D – F:
    G– J: IOS
    K – N: NFK
    O – R: PTT
    S – V: SQL
    W – Z:
    D – F: DS9 DOS
    G– J: HTTP
    K – N:
    O – R:
    S – V: SC TNG TOS
    W – Z: WIN

    helpp mee pleaseee i need to java code for this

  21. Write a java program to declare and initialize two dimensional arrays of 3 x 3. (you
    are free to choose the datatype you want).

  22. if i will input:
    1 2 3 4 5 6
    how it should come to:
    1 2 3
    4 5 6

  23. Write a code for a class that consists of static methods only. Each static method receives a twodimensional
    array to perform a specific operation. Then write a code for another class that contains
    “main” to call the methods and demonstrate their functionality. The list and explanation of the methods
    is provided below.
    1. max_length:
    The max_length method receives an integer type two-dimensional array and returns the
    maximum of the lengths of the row. In two-dimensional arrays each row can have different length.
    The method returns the length that is maximum.
    2. random_fill:
    The method receives an integer type two-dimensional array and an integer (x) and fills the array
    with random values in the range: –x to x.
    3. count_true:
    The method receives a Boolean type two-dimensional array and returns the numbers of “Trues”
    in the array.
    4. replace_negative:
    The method receives an integer type two-dimensional array containing positive and negative
    values and replaces all the negative values with the zero, so that the matrix do not contain a
    negative value.

  24. a valid number can be split up intothese components(in order) 1: A decimal number or an integer. 2: (optional)An'e or;E'.followed by an integerr. aA decimal number can be split up into these components(in order). 1: (optional)A sign character(either'+'or'-'). 2:one of the following format. *one or more digits,followed by a dot'.'. *one or more digits, followed by a dot'.', followed by one or more dogits. *A dot'.',followed by one or more digits An integer can be split up into tese components (in order): *(optional) a sign character (either'+'or'-'). *one or more digits. For example all the following are valid numbers :["2","0089","-0.1","+3.14","-90E3","3e+7","+6e-1","53.5e93","-123.456e789"]g given a string s,return true if s is a valid number Sample input: 0
    Sample output: true Sample input: e Sample output: false any buddy can solve this example before morning tommorrow

  25. How to code this using two dimensional array in java? This is the output.

    Enter 9 integer nubers:
    You Entered:
    3 3 3
    3 3 3
    3 3 3
    Row Sum 1:9 Row Sum 2:9 Row Sum 3:9
    Col Sum 1:9 Col Sum 2:9 Col Sum 3:9

  26. Help please how can I print a hospital report for 3 months performed in 3 different hospitals using single and two dimensional array


Feel free to comment, ask questions if you have any doubt.