Use of Array Class's method toString() and deepToString() in Java


You cannot print array elements directly in Java, you need to use Arrays.toString() or Arrays.deepToString() to print array elements. Use toString() if you want to print one-dimensional array and use deepToString() method if you want to print two-dimensional array.

These methods are overloaded, much like System.out.println() method to accept all primitive types, which means a different method is called if you pass boolean array, and a different one is called when you print integer array.

Same is true with deepToString(), which is used to print two dimensional array in Java. In this Java array tutorial, we will see examples of printing string array, integer array, byte array and a two dimensional array in Java. Rest of them are like that, which means by following these examples, you should be able to print booleancharshortfloatdouble and long array by your own.



Program:

import java.util.Arrays;
/*
*
* Java Program to print arrays in Java using toString()
* and deepToString() method of Arrays class.
*
* @author Piyush Patel
*/

public class PrintArrayInJava
{
public static void main(String args[])
{
// Example 1 : print int array in Java
int[] num = {1,2,3,4,5,6,7,8,9,10};
System.out.println("Numbers : " + num); // Not OK
System.out.println("Numbers : " + Arrays.toString(num)); //Ok
System.out.println("----------------------------------------------");

// Example 2 : print String array in Java
String[] city = {"Rajkot", "Mumbai", "Delhi", "Banglore", "Jamnagar"};
System.out.println("City : " + city);
System.out.println("City : " + Arrays.toString(city));
System.out.println("----------------------------------------------");

// Example 3 : print two dimensional array in Java
String[][] marks = {{"C", "35"}, {"C++", "42"}, {"Java", "51"}};
System.out.println("Marks : " + marks);
System.out.println("Marks : " + Arrays.deepToString(marks));
System.out.println("----------------------------------------------");

// Example 4 : print byte array in Java
String str = "ABC abc 123";
byte[] bytes = str.getBytes();
System.out.println("Bytes : " + bytes);
System.out.println("Bytes : " + Arrays.toString(bytes));
System.out.println("----------------------------------------------");
}
}

OUTPUT:


Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes