MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java Multidimensional Arrays


Multidimensional Arrays are an Array of Arrays. Each elements of an M-D array is an array itself. Marks in the previous example was a 1-D array.

Multidimensional 2-D Array


A 2-D array can be created as follows:
int [][] flats = new int[2][3]          //A 2-D array of 2 rows + 3 columns

We can add elements to this array as follows
flats[0][0] = 100
flats[0][1] = 101
flats[0][2] = 102
// … & so on!

This 2-D array can be visualized as follows:


Similarly, a 3-D array can be created as follows:
String[][][] arr = new String [2][3][4]


Example


package com.company;

public class multi_dim_arrays {
    public static void main(String[] args) {
        int [] marks; // A 1-D Array
        int [][] flats; // A 2-D Array
        flats = new int [2][3];
        flats[0][0] = 101;
        flats[0][1] = 102;
        flats[0][2] = 103;
        flats[1][0] = 201;
        flats[1][1] = 202;
        flats[1][2] = 203;

        // Displaying the 2-D Array (for loop)
        System.out.println("Printing a 2-D array using for loop");
        for(int i=0;i<flats.length;i++){
            for(int j=0;j<flats[i].length;j++) {
                System.out.print(flats[i][j]);
                System.out.print(" ");
            }
            System.out.println("");
        }

    }
}

Output

Printing a 2-D array using for loop
101 102 103
201 202 203


Conclusion

In this page (written and validated by ) you learned about Java Multidimensional Arrays . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java Methods.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.