7.26.2014

Arrays: toString() – Returns string representation of an array

Normally if you want to get  the string representation of the contents of an array, you need to traverse the array using loop constructs. But java.util.Arrays class provides nine overloaded toString() methods to return the string representation of the contents of the specified array which is passed as the only argument to the method.

The string representation consists of a list of the array's elements, enclosed in square brackets ([]). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Elements are converted to strings as by String.valueOf(array_type). Returns "null" if the passed array is null.

Method Declaration:
public static String toString(boolean[] a)
public static String toString(byte[] a)
public static String toString(short[] a)
public static String toString(int[] a)
public static String toString(long[] a)
public static String toString(float[] a)
public static String toString(double[] a)
public static String toString(char[] a)
public static String toString(Object[] a)

Live Example:


import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {
        boolean[] booleanArray = {true, false, false, true, false};
        byte[] byteArray = {7, 0, 2, 6, 1 , 5, 1};
        short[] shortArray = {10, 7, 12, 0, 4, 15, 20};
        int[] intArray = {30, 25, 16 , 26, 40, 35};
        long[] longArray = {111L, 256L, 55L, 280L, 180L};
        float[] floatArray = {3.5F, 0.1F, 6.2F, 2.8F, 4.3F};
        double[] doubleArray = {10.15, 12.40, 7.5, 11.50, 8.9, 6.3};
        char[] charArray = {'x', 'c', 'd', 'a', 'm', 'k', 'j'};
        String[] stringArray = {"egg", "doll", "bat", "cat", "flower", "apple"};
        
        System.out.println("booleanArrary: " + Arrays.toString(booleanArray));
        System.out.println("byteArrary: " + Arrays.toString(byteArray));
        System.out.println("shortArrary: " + Arrays.toString(shortArray));
        System.out.println("intArrary: " + Arrays.toString(intArray));
        System.out.println("longArrary: " + Arrays.toString(longArray));
        System.out.println("floatArrary: " + Arrays.toString(floatArray));
        System.out.println("doubleArrary: " + Arrays.toString(doubleArray));
        System.out.println("charArrary: " + Arrays.toString(charArray));
        System.out.println("stringArrary: " + Arrays.toString(stringArray));
    }  
}


Output: 
booleanArrary: [true, false, false, true, false]
byteArrary: [7, 0, 2, 6, 1, 5, 1]
shortArrary: [10, 7, 12, 0, 4, 15, 20]
intArrary: [30, 25, 16, 26, 40, 35]
longArrary: [111, 256, 55, 280, 180]
floatArrary: [3.5, 0.1, 6.2, 2.8, 4.3]
doubleArrary: [10.15, 12.4, 7.5, 11.5, 8.9, 6.3]
charArrary: [x, c, d, a, m, k, j]
stringArrary: [egg, doll, bat, cat, flower, apple]



Use the social sharing button below to spread the knowledge among others.

0 comments:

Post a Comment