Tuesday 9 April 2024

Convert multidimensional arrays to a string in Java

The Arrays.deepToString() method is a utility method provided in the java.util package in Java. It's used to generate a string representation of nested arrays.

 

When you pass a multidimensional array to Arrays.deepToString(), If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString(e). If an element e is an array, then deepToString() is recursively called on those arrays until all elements are converted into their string representations.

 

DeepToStringDemo.java

package com.sample.app;

import java.util.Arrays;

public class DeepToStringDemo {
	
	public static void main(String[] args) {
		
		int[][] matrix1 = {
				{1, 2, 3}, 
				{4, 5, 6}, 
				{7, 8, 9}
		};
		String matrixString = Arrays.deepToString(matrix1);
		System.out.println("matrix1 : " + matrixString);
		
		int[][][] matrix2 = {
				{
					{1, 2, 3}, 
					{4, 5, 6}, 
					{7, 8, 9}
				},
				
				{
					{10, 11, 12}, 
					{13, 14, 15}, 
					{16, 17, 18}
				}
				
				
		};
		 matrixString = Arrays.deepToString(matrix2);
		System.out.println("matrix2 : " + matrixString);

	}

}

Output

matrix1 : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 : [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]



Previous                                                 Next                                                 Home

No comments:

Post a Comment