The Wayback Machine - https://web.archive.org/web/20241119101530/https://www.geeksforgeeks.org/arrays-deeptostring-in-java-with-example/
Open In App

Arrays.deepToString() in Java with Example

Last Updated : 07 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

java.util.Arrays.deepToString(Object[]) method is a java.util.Arrays class method.

Returns a string representation of the “deep contents” of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings. The simple toString() method works well for simple arrays, but doesn’t work for multidimensional arrays. This method is designed for converting multi-dimensional arrays to strings.

Syntax:

public static String deepToString(Object[] arr)

arr - An array whose string representation is needed

This function returns string representation of arr[].
It returns "null"   if the specified array is null.

Example:

Let us suppose that we are making a 2-D array of
3 rows and 3 column.
    2   3   4   
    5   6   7
    2   4   9

If use deepToString() method to print the 2-D array, 
we will get string representation as :-
[[2,3,4], [5,6,7], [2,4,9]]

Printing multidimensional Array




// A Java program to print 2D array using deepToString()
import java.util.Arrays;
  
public class GfG
{
    public static void main(String[] args)
    {
        // Create a 2D array
        int[][] mat = new int[2][2];
        mat[0][0] = 99;
        mat[0][1] = 151;
        mat[1][0] = 30;
        mat[1][1] = 5;
  
        // print 2D integer array using deepToString()
        System.out.println(Arrays.deepToString(mat));
    }
}


Output:

[[99, 151], [30, 5]]

toString() vs deepToString()
toString() works well for single dimensional arrays, but doesn’t work for multidimensional arrays.




// Java program to demonstrate that toString works if we 
// want to print single dimensional array, but doesn't work
// for multidimensional array.
import java.util.Arrays;
public class Deeptostring
{
    public static void main(String[] args)
    {
        // Trying to print array of strings using toString
        String[] strs = new String[] {"practice.geeksforgeeks.org",
                                      "www.geeksforgeeks.org"
                                     };
        System.out.println(Arrays.toString(strs));
  
        // Trying to print multidimensional array using
        // toString
        int[][] mat = new int[2][2];
        mat[0][0] = 99;
        mat[0][1] = 151;
        mat[1][0] = 30;
        mat[1][1] = 50;
        System.out.println(Arrays.toString(mat));
    }
}


Output:

[practice.geeksforgeeks.org, www.geeksforgeeks.org]
[[I@15db9742, [I@6d06d69c]

Note : We can use a loop to print contents of a multidimensional array using deepToString().

deepToString() works for both single and multidimensional, but doesn’t work single dimensional array of primitives




// Java program to demonstrate that deepToString(strs))
// works for single dimensional arrays also, but doesn't
// work single dimensional array of primitive types.
import java.util.Arrays;
public class Deeptostring
{
    public static void main(String[] args)
    {
        String[] strs = new String[] {"practice.geeksforgeeks.org",
                                      "www.geeksforgeeks.org"
                                     };
        System.out.println(Arrays.deepToString(strs));
          
        Integer []  arr1 = {10, 20, 30, 40};
        System.out.println(Arrays.deepToString(arr1));
          
        /* Uncommenting below code would cause error as 
           deepToString() doesn't work for primitive types
        int []  arr2 = {10, 20, 30, 40};
        System.out.println(Arrays.deepToString(arr2));   */    
    }
}


Output:

[practice.geeksforgeeks.org, www.geeksforgeeks.org]
[10, 20, 30, 40]

Reference:
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[])

.



Similar Reads

Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
How to Sort an Arrays of Object using Arrays.sort()
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array storing any type of object can be Integer, String or
3 min read
Java 8 | DoubleToIntFunction Interface in Java with Example
The DoubleToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToIntFunction type is used to define
1 min read
Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Java.util.Arrays.deepEquals() in Java
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension. Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of eleme
4 min read
Java.util.Arrays.parallelPrefix in Java 8
Prerequisites: Lambda Expressions in Java 8Stream In Java The parallelPrefix method is introduced to the Arrays class in java 8. The parallelPrefix method performs a given mathematical function on the elements of the array cumulatively, and then modifies the array concurrently. Syntax : parallelPrefix(int[] array, IntBinaryOperator op) Parameters :
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Math asin() method with Example
The java.lang.Math.asin() returns the arc sine of an angle in between -pi/2 and pi/2. Arc sine is also called as an inverse of a sine. If the argument is NaN or its absolute value is greater than 1, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument. Syntax : public static double asin(doubl
1 min read
Arraylist lastIndexOf() in Java with example
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found. Prog
2 min read
ArrayList trimToSize() in Java with example
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Syntax: trimToSize() Parameter: It does not accepts any parameter. Return Value: It does not returns any value. It trims the capacity of this
1 min read
ArrayList isEmpty() in Java with example
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element. Syntax: list_name.isEmpty() Parameter: It does not accepts any parameter. Returns: It returns True if the list list_name has no elements else it returns f
2 min read
Java String isEmpty() method with example
Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of the String class is included in Java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0. Syntax of Java
3 min read
Java String contains() method with example
The java.lang.String.contains() method searches the sequence of characters in the given string. It returns true if the sequence of char values is found in this string otherwise returns false. Implementation of contains() methodpublic boolean contains(CharSequence sequence) { return indexOf(sequence.toString()) > -1; } Here conversion of CharSequ
2 min read
Java Math log() method with example
The java.lang.Math.log() method returns the natural logarithm (base e) of a double value as a parameter. There are various cases : If the argument is NaN or less than zero, then the result is NaN.If the argument is positive infinity, then the result is positive infinity.If the argument is positive zero or negative zero, then the result is negative
1 min read
Java String toCharArray() with example
The Java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string. Syntaxpublic char[] toCharArray();Return ValueIt returns a newly allocated character array.Example of Java String toCharArray()Example 1: Java Code // Java program to demonstrate // working of
1 min read
Java log10() with example
The java.lang.Math.log10() is one of the Java Math Library method which is used to return the base 10 logarithmic value of given double value as a parameter. There are various cases : If the argument is positive double value, Math.log10() method will return the logarithm of a given value. If the argument is NaN or less than zero, Math.log10() metho
2 min read
Java log1p() with example
The java.lang.Math.log1p() is one of the Java Math Library method which is used to return the natural logarithm of the sum of the arguments and 1.For the small values, the result of log1p(a) is much closer to the true result of ln(1 + a) than the floating-point evaluation of log(1.0 + a).There are various cases : If the argument is positive double
2 min read
Java Math hypot() method with Example
java.lang.Math.hypot() function is an inbuilt math function in Java that returns the Euclidean norm, [TEX] \sqrt{(x * x + y * y)} [/TEX]. The function returns sqrt(x2 + y2) without intermediate overflow or underflow. If either argument is infinite, then the result is positive infinity. If either argument is NaN and neither argument is infinite, the
1 min read
Java Math exp() method with Example
The java.lang.Math.exp() returns euler's number e raised to the power of a double value. If the argument is NaN, the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument is negative infinity, then the result is positive zero. Syntax : public static double exp(double a) Parameter : a : the expone
1 min read
Java Math getExponent() method with Example
The java.lang.Math.getExponent() returns the unbiased exponent used in the representation of a double or float. Note: If the argument is NaN or infinite of double or float type, then the result is (Double.MAX_EXPONENT + 1) or (Float.MAX_EXPONENT + 1). If the argument is zero or subnormal of double or float type, then the result is (Double.MIN_EXPON
2 min read
Java Math getExponent() method with Example
The java.lang.Math.getExponent() is a built-in math function which returns the unbiased exponent used in the representation of a float. If the argument is NaN or infinite, then the result is Float.MAX_EXPONENT + 1. If the argument is zero or subnormal, then the result is Float.MIN_EXPONENT -1. Syntax: public static int getExponent(float val) Parame
1 min read
Java Math expm1() method with Example
The java.lang.Math.expm1() returns ex -1. Note that for values of x near 0, the exact sum of expm1(x) + 1 is much closer to the true result of ex than exp(x). If the argument is NaN, the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument is negative infinity, then the result is -1.0. If the ar
2 min read
Java Math round() method with Example
The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long. If the argument is NaN, the result is 0. If the argument is negative infinity or any value less than or equal
2 min read
Java toRadians() method with Example
The java.lang.Math.toRadians() is used to convert an angle measured in degrees to an approximately equivalent angle measured in radians. Note: The conversion from degrees to radian is generally inexact. Syntax: public static double toRadians(double deg) Parameter: deg : This parameter is an angle in degrees which we want to convert in radians. Retu
1 min read
Java toDegrees() method with Example
The java.lang.Math.toDegrees() is used to convert an angle measured in radians to an approximately equivalent angle measured in degrees. Note: The conversion from radians to degrees is generally inexact; users should not expect cos(toRadians(90.0)) to exactly equal 0.0. Syntax: public static double toDegrees(double rad) Parameter: rad : This parame
1 min read
Java Math nextAfter() method with Example
The java.lang.Math.nextAfter() returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments are equal then the second argument is returned. Syntax of nextAfter() method// datatype can be float or double. public static dataType nextAfter(dataType st, dataType dir) Parameter : st : starti
2 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Integer.numberOfLeadingZeros() Method in Java With Example
The java.lang.Integer.numberOfLeadingZeros() is the method which returns the total number of zero(0) bits preceding the highest-order (ie.leftmost or most significant "1" bit)one-bit in the two's complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers th
3 min read
Integer.numberOfTrailingZeros() Method in Java with Example
The Java.lang.Integer.numberOfTrailingZeros() is the method which returns the total number of zero(0) bits following the lowest-order (ie.Rightmost or least significant "1" bit)one-bit in the two's complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers
3 min read
three90RightbarBannerImg