2

How do you print objects in a array in java?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Java lover
  • 23
  • 3
  • possible duplicate of [Simplest way to print an array in Java](http://stackoverflow.com/questions/409784/simplest-way-to-print-an-array-in-java) – YoK Sep 09 '10 at 10:40

3 Answers3

6

There are several useful toString() and deepToString() methods in java.util.Arrays class.

String[] strings = { "foo", "bar", "waa" };
System.out.println(Arrays.toString(strings)); // [foo, bar, waa]

An alternative is to just loop over them yourself and print each item separately.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Using Apache Commons Lang:

org.apache.commons.lang.StringUtils.join(Arrays.asList(strings), ", ");

Using Spring Core:

org.springframework.util.StringUtils.collectionToDelimitedString(Arrays.asList(strings), ", ");
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94
1

You can do it using for loop.

Here's example :

  String[] colors = {"red","blue","black","green","yellow"};
  for (String color : colors) {
   System.out.println(color);
  }

Also check : What's the simplest way to print a Java array?

As quoted by Esko in above link is best answer:

In Java 5 Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays.

Note that Object[] version calls .toString() of each object in array. If my memory serves me correct, the output is even decorated in the exact way you're asking.

Community
  • 1
  • 1
YoK
  • 14,329
  • 4
  • 49
  • 67