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?

2
  • System.out.println(Arrays.toString(arr)); should produce identical output there. Commented Aug 24, 2012 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.) Commented Aug 24, 2012 at 23:28

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

9
System.out.println(Arrays.toString(arr));

Comments

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.