File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How to display values in an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to display values in an array" Watch "How to display values in an array" New topic

How to display values in an array

Viidhya Kishore
Ranch Hand

Joined: Jan 03, 2007
Posts: 99
I am having a String[] array.

I need to display all its values separated by commas.

Like Iam having values like 1,2,3,4.

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11497

you need to loop through your array, and print them as you go or build a big long string, then print that when you're done.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24187

Or you could use


but that will enclose your list in [] marks.

[Jess in Action][AskingGoodQuestions]
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 690
Capture the output and substring out the data minus the []s
vaibhav mishra
Ranch Hand

Joined: Jun 18, 2008
Posts: 168
do it in Java 5 way

use enhanced for loop
let string array you want to print is


then code will be

[edit]Corrected code tags. CR[/edit]
[ July 23, 2008: Message edited by: Campbell Ritchie ]

vedha vas

Joined: Jul 22, 2008
Posts: 10
Hi Shriya Kishore ,

Try this way :

String s[] = {new String("1"),new String("2"),new String("3"),new String("4"),new String("5")};
String str = Arrays.asList(s).toString();
System.out.println(str.substring(1, str.length()-1));

Regrads,<br />Vedha.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19783

Instead of Arrays.asList(s).toString(), use Arrays.toString(s). These toString methods, added in Java 5.0, do the same thing without creating the List object.

How To Ask Questions How To Answer Questions
Viidhya Kishore
Ranch Hand

Joined: Jan 03, 2007
Posts: 99
Thanks everyone for your valuable suggestions.
I stuck around wit Rob's and it is good now.

Thanks once again.
I agree. Here's the link:
subject: How to display values in an array