The Java Program: Print.java

  1 // Print.java
  2 import java.util.Arrays;
  3 
  4 class Print {
  5 
  6    public static void main (String[] args) {
  7 
  8       final char [] ca = { 'H', 'e', 'l',  'l', 'o'};
  9       final int [] ia = {1,2,3,4,5,6};
 10 
 11       /*
 12         "System.out" is an instance of "java.io.PrintStream".  The
 13         class "PrintStream" has the overloaded method "println" that
 14         works on types "String" and "char []".
 15       */
 16       System.out.println (ca);   // prints: "hello"
 17 
 18       /*
 19         Arrays, be they char[] or int[] or whatever, do not have a
 20         string conversion other than the default type/location value.
 21         The following line prints something like "Char array:  [C@7bed1c1f"
 22       */
 23       System.out.println ("Char array:  " + ca);
 24       System.out.println ("Char array:  " + ca.toString());
 25 
 26       /*
 27         Try this instead:
 28       */
 29       System.out.println ("Char array:  " + new String (ca));
 30       System.out.println ("Char array:  " + Arrays.toString(ca));  // new in 1.5
 31 
 32       /*
 33         Since no version of "println" exists for "int []", the
 34         "PrintStream.println (Object)" method is used which relies on the
 35         static "String.valueOf(Object)" method and since the object is not
 36         null this results in the string conversion "toString()" method being
 37         called.  For arrays this results in just the type/location value.
 38 
 39         All of the following are the same, and there was no easy way to get a
 40         more 'friendly' version until Java 1.5.
 41       */
 42       System.out.println (ia);
 43       System.out.println (String.valueOf(ia));
 44       System.out.println (ia.toString());
 45       System.out.println (Arrays.toString(ia));
 46 
 47       /*
 48         For arrays of objects ...
 49       */
 50       System.out.println (args);
 51       System.out.println (Arrays.asList (args));
 52       System.out.println (Arrays.toString (args));
 53    }
 54 
 55 }