Print 2D list java

This post will discuss how to print a two-dimensional array in Java.

In the previous post, we have discussed how to declare and initialize two-dimensional arrays in Java. This post will discuss how to print them.

1. Using Arrays.toString() method

We know that a two-dimensional array in Java is a single-dimensional array having another single-dimensional array as its elements. We can use the Arrays.toString() method to print string representation of each single-dimensional array in the given two-dimensional array.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import java.util.Arrays;

class Main

{

// Program to print two-dimensional array in Java

public static void main(String[] args)

{

int[][] arr = {

{1, 2, 3},

{4, 5, 6, 7},

null,

{8, 9}

};

for (int[] ints : arr) {

System.out.println(Arrays.toString(ints));

}

}

}

DownloadRun Code

Output:

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


The above code uses a simple for-loop to print the array. We can also use a for-each loop to print the array effectively, as shown below:

1

2

3

for (int[] row: arr) {

System.out.println(Arrays.toString(row));

}

2. Using Inner for-loop

A naive solution would use two loops the outer loop for the first dimension and the inner loop for the second dimension of the two-dimensional array.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import java.util.Arrays;

class Main

{

// Program to print two-dimensional array in Java

public static void main(String[] args)

{

int[][] arr = {

{1, 2, 3},

{4, 5, 6, 7},

null,

{8, 9}

};

for (int i = 0; i < arr.length; i++)

{

for (int j = 0; (arr[i] != null && j < arr[i].length); j++) {

System.out.print(arr[i][j] + " ");

}

System.out.println();

}

}

}

DownloadRun Code

Output:

1 2 3
4 5 6 7

8 9


Heres how we can use a for-each loop to print the array effectively:

1

2

3

4

5

6

7

8

9

10

11

for (int[] row: arr)

{

if (row != null)

{

for (int col: row) {

System.out.print(col + " ");

}

}

System.out.println();

}


Since an array is an object in Java, it can be null. The null check in the above code is placed to avoid NullPointerException if any array is null.

Thats all about printing two-dimensional arrays in Java.