how to print a 2d array in java

ww‮‬w.lautturi.com
how to print a 2d array in java

method 1

/**
 * @author lautturi.com
 * Java example: output 2d array in java
 */

import java.util.*;

import org.json.JSONArray;
import org.json.JSONObject;

public class Lautturi {

	public static void main(String[] args) {

		int array[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
		System.out.println(Arrays.deepToString(array));

	}
}

output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

method 2

/**
 * @author lautturi.com
 * Java example: print 2-dimensional array in java
 */

import java.util.*;

import org.json.JSONArray;
import org.json.JSONObject;

public class Lautturi {

	public static void main(String[] args) {

		int array[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
		for (int row = 0; row < array.length; row++) {
			for (int col = 0; col < array[row].length; col++) {
				System.out.printf("%5d", array[row][col]);
			}
			System.out.println();
		}

	}
}

output:

1    2    3    4
    5    6    7    8
    9   10   11   12
Created Time:2017-09-12 22:35:24  Author:lautturi