4

I am currently working with arrays, and everytime I need to print one I do a for loop.

System.out.print("[");
for(int i = 0; i < arr.length; i++){
    System.out.print(arr[i] + ", ");
}
System.out.println("]");

This seems like a feature that would be built into java (I am using java). Is there a built in way to print arrays?

ceptno
  • 687
  • 2
  • 6
  • 28
  • `System.out.println(Arrays.toString(arr));` should produce identical output there. – obataku Aug 24 '12 at 23:19
  • 2
    (Remember that it is possible always write a single function and use it later .. not that it is [necessarily] warranted here, but "every time" is too much typing. Also, separate the operations to reduce coupling: turning the array into a string representation and outputting said string.) –  Aug 24 '12 at 23:28

3 Answers3

12

You could use: Arrays.toString(arr) for normal arrays and/or Arrays.deepToString(arr) for arrays within arrays. Both these methods return the string representation of the array.

See the Arrays docs for more.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
9
System.out.println(Arrays.toString(arr));
Joe K
  • 18,204
  • 2
  • 36
  • 58
0

You could also write your own method that does the same thing as Arrays.toString():

/** Converts an array into a CSV string. */

public static <T> String arrayToCsv(T[] someArray) {

    if (someArray == null || someArray.length == 0) {
        return "";
    }

    StringBuilder csv = new StringBuilder();

    for (T thisT : someArray) {
        String val = (thisT == null) ? "null" : thisT.toString();
        csv.append(val).append(", ");
    }

    return csv.toString();
}

Test it:

Double[] doubleArray = { 2.4, 3.6, 6.5 };
String[] stringArray = { "foo", "bar", "baz" };

System.out.println(arrayToCsv(doubleArray));
System.out.println(arrayToCsv(stringArray));
jahroy
  • 22,322
  • 9
  • 59
  • 108