57

Is there any function in java like toString() to print a String array?

This is a silly question but I want to know if there is any other way than writing a for loop.

Thanks.

priyank
  • 4,634
  • 11
  • 45
  • 52

7 Answers7

97
String[] array = { "a", "b", "c" };
System.out.println(Arrays.toString(array));
Mike
  • 19,267
  • 11
  • 56
  • 72
  • When I think string joining I normally think String joining with delimiters, except in very specific situations. – TheLQ Aug 14 '10 at 03:52
  • What if we have an array of strings, and want simple output; like: `String[] array = {"John", "Mahta", "Sara"}`, and we want this output without bracket and commas: `John Mahta Sara`? – Hengameh Aug 29 '15 at 02:35
12

With Apache Commons Lang,

System.out.println(StringUtils.join(anArray,","));
TheLQ
  • 14,830
  • 14
  • 69
  • 107
5

There is the Arrays.toString() method, which will convert an array to a string representation of its contents. Then you can pass that string to System.out.println or whatever you're using to print it.

David Z
  • 128,184
  • 27
  • 255
  • 279
2

If you need a bit more control over the string representation, Google Collections Joiner to the rescue!

String[] myArray = new String[] {"a", "b", "c"};
String joined = Joiner.on(" + ").join(myArray);
// =>  "a + b + c"
Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
1

I think you are looking for

System.out.printf(String fmtString, Object ... args)

Where you specify the format of the output using some custom java markup (this is the only part you need to learn). The second parameter is the object, in your case, the array of strings.

More information: Using Java's Printf Method

adu
  • 947
  • 1
  • 8
  • 15
1

With op4j,

String[] myArray = new String[] {"a", "b", "c"};

System.out.println(Op.on(myArray).toList().get());
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
domgom
  • 283
  • 2
  • 9
0
String[] values= { ... }
System.out.println(Arrays.asList(values));
Steve B.
  • 55,454
  • 12
  • 93
  • 132
  • What if we have an array of strings, and want simple output; like: `String[] array = {"John", "Mahta", "Sara"}`, and we want this output without bracket and commas: `John Mahta Sara`? – Hengameh Aug 29 '15 at 02:36