The easy way to do this is just use Arrays.toString
public static void printArray(int[] myArray)
{
System.out.print( Arrays.toString( myArray ) );
}
Note this prints brackets instead of braces. In the interest of completeness, if you do implement this yourself, don't forget to check for the array being null in addition to other boundary conditions like length = 0.
Here is an example using StringBuilder, where I just always remove the last two characters after checking for null and length = 0. If you have a very complicated string to calculate for each item in a list/array, this can be easier than copying the code to make each item outside the loop, and can be slightly faster than checking for i==array.length-1 each time through the loop.
public class MyArraysToString
{
public static void main( String[] args )
{
int[] test = { 8, 7, 6, 5, 4, };
printArray( test );
System.out.println( myToString( null ) );
System.out.println( myToString( new int[0] ) );
System.out.println( myToString( test ) );
}
public static void printArray( int[] myArray )
{
System.out.println( Arrays.toString( myArray ) );
}
public static String myToString( int[] a ) {
if( a == null ) return "null";
if( a.length == 0 ) return "{}";
StringBuilder sb = new StringBuilder();
sb.append( '{' );
for (int i = 0; i < a.length; i++) {
sb.append( a[i] );
sb.append( ", " );
}
sb.setLength( sb.length()-2 );
sb.append( '}' );
return sb.toString();
}
}
", ", check the length ofmyArrayand the value ofito determine if you need to append", ".StringBuilder, then just always remove the last space and comma.StringBuilderis just achar[]under the hood, so removing two characters from the end is easy. The resulting code is pretty compact and efficient too.printArraymethod, only print the array. Having it also initialise the array is a confusing complication missed by some answering the question. You could call the methodinitialiseAndPrintArray