ArrayTest.java

Download this source file

// ArrayTest: How well do you understand arrays?
//
// Written 2003 by Wayne Pollock, Tampa Florida USA

class ArrayTest
{
   public static void main ( String [] args )
   {
      int [] array = { 'H', 'e', 'l', 'l', 'o' };
      byte [] barray = { 'H', 'e', 'l', 'l', 'o' };
      char [] carray = { 'H', 'e', 'l', 'l', 'o' };

      // Will this work, fail to compile, or throw an Exception?
      int [] copy = (int[]) array.clone();

      // What is the output?

      System.out.println( array );
      System.out.println( barray );
      System.out.println( carray );
   }
}

See the Answer






























Answer

Although java.lang.System.arraycopy can be used to flexibly copy arrays, all arrays support the Clonable interface.  So array.clone() works just fine to copy a whole array.

As for the output statements, when any object is printed Java auto-magically invokes that object's toString method.  Most objects use the inherited Object.toString() method, which prints out a unique string for each object.  This string contains the class name (which for arrays of primitive types can look quite strange), an '@' (at-sign), and a hexidecimal number (the hashcode of the object).

For array and barray, it is this Object.toString() method that gets used.  However char arrays use a custom toString method that displays the sequence of characters in the array as a String.  So the output of this program is something like this (actual hex numbers may vary from what you see if you run this program):

[I@17182c1
[B@13f5d07
Hello

Send comments and questions to pollock@acm.org.
Valid HTML 4.01!   Valid CSS!   CAST: Bobby WorldWide Approved 508   CAST: Bobby WorldWide Approved AAA