Jump to Real's How-to Main page

Dump array content

Convert the array to a List and then convert to String. This technique works only with classes and not with primitives like int or double.
public class Test {
  public static void main(String args[]) {
    String s[] = {"a", "b", "c", "d"};

    System.out.println(java.util.Arrays.asList(s).toString());
    // output
    // [a, b, c, d]
  }
}

JDK1.5
java.utils.Arrays provides new ways to dump the content of an array. It's even possible to dump muti-dimensional arrays.

public class Test {
  public static void main(String args[]) {
    String s[] = {"a", "b", "c", "d"};
    double d [][]= {
        {0.50, 0.70,  0.40, 0.60},
        {0.50, 1.10,  0.50, 0.80}
    };
    System.out.println(java.util.Arrays.toString(s));
    System.out.println(java.util.Arrays.deepToString(d));
    // output
    // [a, b, c, d]
    // [[0.5, 0.7, 0.4, 0.6], [0.5, 1.1, 0.5, 0.8]]
  }
}
You can also use the new shorthand notation to iterate through an array :
public class Test {
  public static void main(String args[]) {
    String s[] = {"a", "b", "c", "d"};
    for (String element : s)
      System.out.println(element);
  }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]