• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Array » Multidimensional Array in Java Example
Next →
← Prev

Multidimensional Array in Java Example

By Dinesh Thakur

Multi-dimensional arrays that contain more than one index and can store information in multiple dimensions.  The most common one is a two-dimensional array, also called a matrix or table. In the two-dimensional array, each element associated with two indexes.  We can visualize the two-dimensional array as a spreadsheet, rectangular in shaper and containing elements that divided into columns and rows. However, Java does not indeed support multidimensional arrays. However, one can achieve the same functionality by declaring an array of arrays.

In order to understand arrays of arrays, consider an example where we want to calculate the marks obtained by 4 students of a class in 3 different subjects. An obvious way to store information is in a two-dimensional array (or matrix) which we call marks. In order to create this two dimensional array marks, we are set up much like the arrays we looked at previously but with one difference – two sets of the square brackets. The first set is for the rows and the second set is for the columns. In the code line right above the code, we informed Java that we need an array with 4 rows and 3 columns. Storing values in a multi-dimensional array require care that each row and each column is tracked. 

The two-dimensional array marks of int type can be declared as follows,

int [][] marks;

The above declaration can also be written as,

int[] marks[];

int marks [][] ;

Each of the pairs of square brackets represent one dimension. This statement creates a variable marks that will refer to a two- dimensional int array.

Once you have declared an array variable, you can create an array that it will reference using the following statement,

marks = new int [4][3] ;

On execution of this statement, the JVM creates an array with 4 elements and stores a reference to this array in the variable marks. Each of these four elements is actually a reference variable referring to a (newly created) int array with 3 elements. In the two-dimensional array marks, the first index corresponds to a student and second index corresponds to a subject.

                   Multidimensional Array in Java Example

You can combine the declaration and instantiation of the above array in a single statement as follows,

int [][] marks = new int[4][3];

Once this two-dimensional array has been created, an individual element is accessed by indexing the array. Separate index must be provided for each dimension, each of which begins at 0. So in order access marks obtained by 2nd student in 3rd subject can be written as

marks[1][2] // remember arrays are 0 based

As we can calculate the length of one dimensional array using the length field. Similarly, in multidimensional arrays, we can calculate the length of each dimension.  In our example, the length of the first dimension can be calculated by using the following,

marks.length

The length of the second dimension can be calculated using marks[i].length where i ranges from 0<=i<=3.

Accessing all of the items from any multi-dimensional array requires the use of a  loop within a loop. Look at the code below where we use a double-loop to access  all our numbers: 

The complete program is as follows,

import java.util.Scanner; 
public class twoDArray
{
     public static void main(String[] args)
     {
            int[] [] a = new int[3] [2];
            int i, j;
            Scanner input=new Scanner(System.in);
            System.out.print("Enter the Elements of 3 * 2 Matrix :");
            for(i=0;i<3; i++)
                {
                   for(j=0; j<2;j++)
                   a[i] [j]=input.nextInt();
                }
            System.out.println("Elements in Matrix from are :");
            for(i=0;i<3;i++)
                { 
                   for(j=0; j<2; j++)
                       System.out.print(a[i][j]+" ");
                       System.out.println();
                }
       }
}

Multidimensional Array in Java

The initial for loop is used for the rows and the second one is used for the columns. With the first loop, 0 is the value of the i variable. In the for loop, the code is another loop, and the entire double loop is executed for as long as the i variable value stays as 0. The second loop has another variable, named j and both variables, i and j, are used to access the array: 

a[i][j].
We use the double loop system for looping through multi-dimensional array values, one row at a time.

Creating a Two-Dimensional Array

We can do these in three separate ways:   

Using Just an Initializer  

To use just an initializer to create the two-dimensional array, we use the following  
syntax: 

‘{‘[rowinit (‘,’ rowinit)*]’}’  
rowinit has the following syntax:  
‘{‘[expression (‘,’ expression)*]’}’  
With this syntax, we are saying that a two-dimensional array is optional, and it is a  list containing row initializers, each separated by a comma, and all in between a set of curly braces. Each of the row initializers is also an optional list, this time expressions, again with the comma separation and in between a pair of curly braces.   Similar to the one-dimensional array, the expressions all have to evaluate types that are compatible.  
Have a look at this example:  
{{21.5, 31.6, 29.3}, {-39.7, -19.3, -17.2 }}   

Using Just the New Keyword 

When we use the new keyword, it allocates the memory for the array and returns the array reference. It is the syntax:  
‘new’ type ‘[‘ int_expression1 ‘]’ ‘[‘int_expression2 ‘]’  
We are saying that the two-dimensional array is a region of int_expr1, which are positive, row elements and int_expr2, also positive, column elements, all with the same data type. Not only that, every element has been zeroed.  
Have a look at this example:  
new double[2][3] // Create a two row by three column table.  
Using Both Initializer and the New Keyword  
Using both has a syntax approach of:  
‘new’ type ‘[‘ ‘]’ [‘ ‘]’ ‘{‘[rowInit (‘,’ rowInit)*]’}’  
rowInit has a syntax of:  
‘{‘[expression (‘,’ expression)*]’}’  
It is a combination of the syntax from the previous examples; note that there is no int_expr in between either the sets of square brackets because we can already work out how many elements are in the array just by looking at expressions list.  
Have a look at this example:  
new double [][] {{ 21.5, 31.6, 29.3}, {-39.7, -19.3, -17.2}} 

You’ll also like:

  1. What is Array in Java? – Definition, Declare, Create, Initialize [Example]
  2. Multidimensional Arrays in C
  3. Multidimensional Arrays and Pointers in C
  4. One dimensional array – Java Examples
  5. Largest Number in an Array Java Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW