Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax For Declaring Multidimensional Arrays
3.
Two Dimensional Array
3.1.
Initialization of a Two-dimensional Array
3.2.
Accessing Elements in a Two dimensional Array 
3.3.
Example
4.
Three Dimensional Array
4.1.
Initialization of a Three-Dimensional Array
4.2.
Accessing Elements in a Three-Dimensional Array
4.3.
Example
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Multi-Dimensional Arrays in Java

Author Rhythm Jain
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In Java, an array is a collection of variables with similar types referred to by a common name. Arrays in Java behave differently than arrays in C/C++. All Array in Java are allocated dynamically. Since arrays are objects in Java, we may use the object attribute length to determine their size.

Depending on the definition of the array, an array can include object (or non-primitive) as well as primitives (int, char, etc.)  references to a class. The actual values of primitive data types are stored in contiguous memory regions. The real objects of class objects are stored in a heap segment.

The dimension of an array is defined by its size. A two-dimensional array, for example, would have two sizes grouped in the shape of a table. Each array element has a unique index that determines its location within the array. The data is organized in rows and columns or numerous rows and columns.

Also see, Duck Number in Java and Swap Function in Java

Syntax For Declaring Multidimensional Arrays

data_type[1st dimension][2nd dimension][]..[Nth dimension] name_array = new data_type[size1][size2]….[sizeN];

data_type: Type of data to be stored in the array. E.g., int, String, etc.

Dimension: The dimension of the array created. E.g., 1D, 2D, 3D, so on.

name_array: Name of the array created.

size1, size2, …, sizeN: Sizes of the different dimensions.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Two Dimensional Array

As previously stated, a two-dimensional array is the most basic sort of multi-dimensional array. A multidimensional array of size m x n can be represented as a table with n rows and m columns.

The syntax for declaration of a Two-Dimensional Array is:

data_type[ ][ ] array_name = new data_type[size1][size2];

Example

Int[ ][ ] rank = new int[4][4]; 

Number of elements= 4 *4= 16.

Initialization of a Two-dimensional Array

One method of initialization is to assign all the values at the time of declaration of the array.

For example

Int[ ][ ] rank = { {2, 1, 3}, {4, 5, 6}, {7, 8, 9} };

Other way to initialize the array first and then assign values.

Int[ ][ ] rank = new int[3][3]; 
rank[0][0]=1; rank[0][0]=2; rank[0][0]=3;
rank[0][0]=4; rank[0][0]=5; rank[0][0]=6;
rank[0][0]=7; rank[0][0]=8; rank[0][0]=9;

                                          

Accessing Elements in a Two dimensional Array 

Let the above table represent the above-defined array. The first element in the array is generally referenced as rank [0][0], the next element in the same row is referenced as rank [0][1]. The elements of the next row can be accessed as rank[1] [0], rank [1][1]. 

Hence, we reference it using the index to access a particular element. 

The syntax for it can be defined as:

array_name [number of row] [number of column]

Example

rank [1] [2]; // gives us the value of the first row and second column

Let us now look at a code segment that helps us understand how the elements of a two-dimensional matrix are accessed. 

Example

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


        int[][] rank = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
        for (int i = 0; i <= 2; i++) {
            for (int j = 0; j <= 2; j++) {
                System.out.print(rank[i][j] + " ");
            }
    
            System.out.println();
        }
    }
}

Output:

1 2 3
4 5 6
7 8 9

 

You can also read about the topic of Java Destructor and Hashcode Method in Java.

Three Dimensional Array

A three-dimensional array is made up of three arrays joined together. As a result, it can be represented as an array of two-dimensional arrays. A three-dimensional array is a more complicated type of multidimensional array.

The syntax for declaration of a three-dimensional array is:

Data_type[ ][ ][ ] array_name=new data_type[size1][size2][size3];

Example

Int[ ][ ][ ] matrix = new int[2][3][4];

Hence, the total elements will be 2*3*4= 24.

Initialization of a Three-Dimensional Array

One method of initialization is to assign all the values at the time of declaration of the array.

Int[ ][ ][ ] rank = { { {2,1}, {3,4}, {5,6} },{ {7,8}, {9,10}, 11,12} } };

Another way to initialize the array first and then assign values.Just as in the case of Two-Dimensional Array.

Int[ ][ ][ ] rank = new int[2][2][2]; 
rank[0][0][0]=1; rank[0][0][1]=2; rank[0][1][0]=3; rank[0][1][1]=4;
rank[1][0][0]=5; rank[1][0][1]=6; rank[1][1][0]=7; rank[1][1][1]=8;

Accessing Elements in a Three-Dimensional Array

The elements of a three-dimensional array can be accessed just as we accessed the elements in the two-dimensional arrays. 

For example:

int matrix [1][1][1];

The element in the first row and first column of the first array in the stated 3D array is represented by the example above.

Lets look at an example.

Example

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


        int[ ][ ][ ] rank = new int[2][2][2]; 
        rank[0][0][0]=1; rank[0][0][1]=2; rank[0][1][0]=3; rank[0][1][1]=4;
        rank[1][0][0]=5; rank[1][0][1]=6; rank[1][1][0]=7; rank[1][1][1]=8;


        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print("[ ");
                for (int k = 0; k < 2; k++) {
                    System.out.print(rank[i][j][k] + " ");
                }
                System.out.print("]");
            }
    
            System.out.println();
        }
    }
}

Output

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

 

Practice it on online java compiler.

Must Read Array of Objects in Java.

Frequently Asked Questions

  1. Can we access elements outside the scope of an array?
    JVM will give ArrayIndexOutOfBoundsException indicating that the array has been accessed with an illegal index
     
  2. Can we use array to store data items of different types?
    No only data items that correspond to data items of which the array was declared can only be inserted in the array.
     
  3. Can we store any Number of items in Multidimentional Array?
    The number of items to be stored in Multi-dimensional arrays should be known in advance.

Key Takeaways

In this blog, we examined multidimensional arrays and related concepts. Two forms of multi-dimensional arrays, Two Dimensional Arrays and Three Dimensional Arrays, were thoroughly explored, including methods for accessing and publishing the values of their various elements. 

Check out this problem - Search In Rotated Sorted Array

If you want to learn more about Java from experts, you can check out the Basics of Java with Data Structures and Algorithms course by coding ninjas.

Happy Coding!

 

Previous article
Single Dimensional Array
Next article
Java Array Indexof
Live masterclass