search
HomeJavajavaTutorialPrint 2D Array in Java

Print 2D Array in Java

Aug 30, 2024 pm 03:27 PM
java

When we want to store elements for a similar type in Java, we take the name of Array. Array stores elements of similar type viz: integer, string, etc. Moreover, the dimension of the array also varies in Java according to your requirements. Therefore, whenever you have data in a 2D array, you need to print those elements.

There are different types of techniques, those you can choose for printing the elements of a two-dimensional array in java. You can use any of those techniques for printing the elements of a two-dimensional array.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

All of the techniques, which I will be showing here, have associated examples of codes. Those will provide you with better insights and practical hands-on. You should see carefully the codes that have inline comments to provide better readability. I have also provided outputs in the form of screenshots at the end of each code.

Let us see the techniques one by one. We will start with the syntax first.

Syntax of 2D Array in Java

In the case of the 2D array, the values are stored in a matrix format, which means it is based on row and column index. You can follow any of the below syntaxes for the declaration of an array in java.

Syntax:

dataType[][] reference_variable name;
dataType [][]reference_variable name;
dataType reference_variable name [][];
dataType []reference_variable name [];

You can follow the below example to create an instance of a two-dimensional array in java of integer type; the number of rows and columns here is 5.

int[][] matrx=new int[5][5];

You can follow the below example for the initialization of a 2D Array in Java.

matrx [0][0]=51;
matrx [0][1]=62;
matrx [0][2]=73;
matrx [1][0]=84;
matrx [1][1]=95;
matrx [1][2]=46;
matrx [2][0]=37;
matrx [2][1]=18;
matrx [2][2]=29;

Examples to Print 2D Array in Java

Below are some examples of how to print a 2d array in java:

Example #1 – Two Dimensional Array of the Same Number of Rows and Columns

In the below example, we will show an example of how to print an array of integers in java.

Code:

public class Print2DArrayInJava {
public static void main(String[] args) {
//below is declaration and intialisation of a 2D array
final int[][] matrx = {
{ 11, 22},
{ 41, 52},
};
for (int r = 0; r 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500286971518.png?x-oss-process=image/resize,p_40" class="lazy" alt="Print 2D Array in Java" ></p>
<h4 id="Example-Jagged-Array-in-Java">Example #2 – Jagged Array in Java</h4>
<p>When a number of rows and columns are not equal in a multidimensional array in java, we call it a Jagged array in Java. Here the number of columns differs from that of its rows.</p>
<p>In the below example, we will show an example of how to print a jagged array of integers in java.</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">public class PrintJaggedArrayInJava {
public static void main(String[] args) {
//below is declaration of a jagged 2 D array
int matrx[][] = new int[2][];
matrx[0] = new int[3];
matrx[1] = new int[5];
//initiatiation of a jagged 2 D array
int cnt = 1;
for (int r=0; r<matrx.length r for c="0;" matrx cnt of a jagged d array system.out.print system.out.println new line>
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500287062670.png?x-oss-process=image/resize,p_40" class="lazy" alt="Print 2D Array in Java" ></p>
<h4 id="Example-Two-Dimensional-Array-of-String-in-Java">Example #3 – Two Dimensional Array of String in Java</h4>
<p>In the below example, we will show an example of how to print a 2D array of strings in java.</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">public class Print2DArrayInJava {
public static void main(String[] args) {
//below is declaration and intialisation of a 2D array of strings
String[][] matrx = {{"OnePlus", "Pixel"}, {"Apple", "Oppo"}};
for (int r = 0; r 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500287224573.png?x-oss-process=image/resize,p_40" class="lazy" alt="Print 2D Array in Java" ></p>
<h3 id="Top-Methods-to-Print-D-Array-in-Java">Top 3 Methods to Print 2D Array in Java</h3>
<p>Methods for printing 2d arrays in java are explained below:</p>
<h4 id="Method-Using-for-Loop">Method #1 – Using for Loop</h4>
<p>For loop is used for iteration, and hence we will use for loop to iterate elements of an array in java.</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">public class PrintUsingForLoop {
public static void main(String[] args) {
final int[][] ar = {
{ 5, 9 },
{ 2, 4 }
};
for (int r = 0; r 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500287386360.png?x-oss-process=image/resize,p_40" class="lazy" alt="Print 2D Array in Java" ></p>
<h4 id="Method-Using-for-each-Loop">Method #2 – Using for-each Loop</h4>
<p>To traverse through an array, we can also use the for-each loop.</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">import java.util.*;
public class PrintUsingForEachLoop {
public static void main(String[] args) {
int[][] rec = new int[2][2];
rec[0][0] = 15;
rec[0][1] = 25;
rec[1][0] = 35;
rec[1][1] = 45;
for(int[] rc: rec){  //using for each loop
System.out.println(Arrays.toString(rc));
}
}
}

Output:

Print 2D Array in Java

Method #3 – Using Arrays.deepToString() Method

Here we will use Arrays.deepToString() method of java.util.Arrays package does a deep conversion into a string of an array. To use this method, we need to import the package java.util.Arrays.

Code:

import java.util.*; //import package
public class PrintUsingDeepToString {
public static void main(String[] args) {
int[][] rec = {{37, 57}, {47, 58}};
System.out.println(Arrays.deepToString(rec)); //deep conversion
}
}

Output:

Print 2D Array in Java

In the above output, the levels of square brackets denote the dimension of the array, which is 2.

Conclusion

So, in this module, we have learned about different techniques on how to print 2 D array in Java. This is nothing new if we compare it to print single dimensional array, except the fact that you need to modify in the declaration, initialization and printing part of the code carefully. If you are a master in a single-dimensional array, this will be just an extension of that. I have also put code examples. You need to exercise those and tally your output with the given outputs. Hands-on by yourself is a must in order to master coding.

The above is the detailed content of Print 2D Array in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is Java mainly for? Analysis of the main uses of Java in actual developmentWhat is Java mainly for? Analysis of the main uses of Java in actual developmentMay 16, 2025 pm 02:54 PM

Java is mainly used to build desktop applications, mobile applications, enterprise-level solutions and big data processing. 1. Enterprise-level applications: Support complex applications such as banking systems through JavaEE. 2. Web development: Use Spring and Hibernate to simplify development, and SpringBoot quickly builds microservices. 3. Mobile applications: Still one of the main languages ​​for Android development. 4. Big data processing: Hadoop and Spark process massive data based on Java. 5. Game development: suitable for small and medium-sized game development, such as Minecraft.

How to set java to Chinese Java development tool Chinese interface setting tutorialHow to set java to Chinese Java development tool Chinese interface setting tutorialMay 16, 2025 pm 02:51 PM

How to set Java development tools to Chinese interface? It can be implemented through the following steps: Eclipse: Window->Preferences->General->Appearance->I18nsupport->Language->Chinese(Simplified), and then restart Eclipse. IntelliJIDEA: Help->FindAction->Enter "switchlanguage"->Select "SwitchIDELanguage&q

How long does it take to learn Java to work? Java learning cycle and employment time estimatesHow long does it take to learn Java to work? Java learning cycle and employment time estimatesMay 16, 2025 pm 02:48 PM

It usually takes 6 to 12 months to learn Java and reach work level, and it may be shortened to 3 to 6 months for those with a programming foundation. 1) Learners with zero foundation need to master the basics and commonly used libraries for 6-12 months. 2) Those with programming foundation may master it within 3-6 months. 3) After 9-18 months of employment, actual projects and internships can accelerate the process.

What is new in java? The memory allocation process of new operatorWhat is new in java? The memory allocation process of new operatorMay 16, 2025 pm 02:45 PM

In Java, the new operator is used to create an object, and its processes include: 1) allocating space in heap memory, 2) initializing the object, 3) calling the constructor, and 4) returning the object reference. Understanding these steps can help optimize memory usage and improve application performance.

How to define arrays in java Syntax format description of array declarationHow to define arrays in java Syntax format description of array declarationMay 16, 2025 pm 02:42 PM

The syntax for defining arrays in Java is: 1. Data type [] Array name = new data type [array length]; 2. Data type Array name [] = new data type [array length]; 3. Data type [] Array name = {element list}; Array is an object, can be null, and the subscript starts from 0. When using it, you need to pay attention to potential errors such as NullPointerException and ArrayIndexOutOfBoundsException.

Usage of new keywords in java Detailed explanation of creating object instances of new keywordsUsage of new keywords in java Detailed explanation of creating object instances of new keywordsMay 16, 2025 pm 02:39 PM

The new keyword is used in Java to create object instances. 1) It tells the JVM to allocate memory and call the constructor to initialize the object. 2) Use new to force new objects to create even if the content is the same. 3) The constructor allows custom initialization. 4) Frequent use of new may lead to performance problems and memory leaks. 5) It is necessary to use try-catch to handle possible exceptions. 6) Anonymous internal classes are advanced usage of new.

Java Chinese garbled solution Several skills for character encoding conversionJava Chinese garbled solution Several skills for character encoding conversionMay 16, 2025 pm 02:36 PM

To solve the problem of Chinese garbled in Java, you can use the following steps: 1. Set the correct character encoding, such as UTF-8 or GBK, to ensure that the file, database and network communication use the same encoding. 2. Use Java's character encoding conversion class to perform necessary encoding conversion. 3. Verify whether the encoding is correct through debugging tools and logs to ensure that the Chinese display is normal in different environments.

What are the two categories of exceptions in Java? The difference between checked and non-checked exceptionsWhat are the two categories of exceptions in Java? The difference between checked and non-checked exceptionsMay 16, 2025 pm 02:33 PM

Exceptions in Java are divided into checked exceptions and non-checked exceptions. Check-type exceptions must be handled explicitly, otherwise the compiler will report an error, which is often used to recover errors, such as a file not found; non-checked exceptions do not need to be handled explicitly, and are often used for programming errors, such as a null pointer exception.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment