This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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: 11855

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: 24189

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: 691
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: 20078

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
It's not a secret anymore!