Array to String

In this chapter you will learn:

  1. How to convert array to string in Java
  2. How to convert multi-dimensional array to string

Convert array value to a String

The following methods returns a string representation of the contents of the specified array. Those methods are often used during debug.

  • static String toString(boolean[] a)
  • static String toString(byte[] a)
  • static String toString(char[] a)
  • static String toString(double[] a)
  • static String toString(float[] a)
  • static String toString(int[] a)
  • static String toString(long[] a)
  • static String toString(Object[] a)
  • static String toString(short[] a)

The following code demonstrates how to use toString method to convert array to String.

import java.util.Arrays;
// j  a  v  a  2  s. c  om
public class Main {

  public static void main(String[] args) {
    byte[] b1 = new byte[] { 3, 2, 5, 4, 1 };
    System.out.println(Arrays.toString(b1));

    Arrays.sort(b1);
    System.out.println(Arrays.toString(b1));
    

    byte[] b2 = new byte[] { 5, 2, 3, 1, 4 };
    Arrays.sort(b2, 1, 4);

    System.out.println(Arrays.toString(b2));
  }

}

The output:

Deep to multi-dimensional string

static String deepToString(Object[] a) returns a string representation of the "deep contents" of the specified array.

import java.util.Arrays;
//from  j  a v  a2 s .  com
public class Main {
  public static void main(String args[]) {
    String s[] = {"a", "b", "c", "d"};
    double d [][]= {
        {0.50, 0.20,  0.20, 0.30},
        {0.50, 1.10,  0.50, 0.80},
        {0.50, 0.70,  0.40},
        {0.50, 0.70},
        {0.50},
    };
    System.out.println(Arrays.toString(s));
    System.out.println(Arrays.deepToString(d));
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to reverse elements in an array
  2. Reverses the order of the given long type value array
Home » Java Tutorial » Array
Java Array
Create an Array
Array Index and length
Multidimensional Arrays
Array examples
Array copy
Array compare
Array Binary search
Array Search
Array sort
Array to List
Convert array to Set
Array fill value
Array to String
Array element reverse
Array element delete
Array shuffle
Array element append
Array min / max value
Sub array search
Get Sub array
Array dimension reflection
Array clone