Home : Course Map : Chapter 4 : Java :
More about Arrays
JavaTech
Course Map
Chapter 4

Introduction
Inheritance
  Demo 1
Overriding
  Demo 2a
  Demo 2b
this,super
MoreConstructors
  Demo 3
Abstraction
Interface 
  Demo 4
Casting References
MoreAboutArrays
Object class
Class Summary
Exercises

    Supplements
Override/Overload
Annotation-J2SE5.0
Java Security
Class Loading
Class Verifier
SecurityManager
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

In the previous chapter we introduced arrays of primitive type values. They generally work in a similar manner as a C programmer would expect. For example, to create an array of 10 integers we could use the following :

  int iArray[] = new int[10];

This creates a buffer of ten int type memory locations with the value of 0 in each.

For arrays of objects, however, the array declaration only creates the array of references for a particular type. It does not create objects of that type. That requires an additional step.

For example, lets say we want to create an array of five String objects. We first create an array of String types:

  String [] strArray = new String[5];

When the array is created, each element contains the special "null" reference value that points nowhere. So if we followed the above declaration with an attempt to use a String method, as in,

   int numChars = strArray[0].length();

an error message will result:

   Exception in thread "main"
   
java.lang.NullPointerException at
    ArrayTest.main(ArrayTest.java:8)

We need to create an object for each array element to reference. For example,

  strArray[0] = new String("Alice");
  strArray[1] = new String("Bob");
  strArray[2] = new String("Cindy");
  strArray[3] = new String("Dan");
  strArray[4] = new String("Ed");

sets each element to reference a particular string.

Note: For convenience, Java allows an alternative form of declaration for String objects :

    strArray[0] = "Alice";

While this is convenient, it only works for string objects and so we use the general form for creating objects via the new operator.

Array Copying

A copy of an array can be made with the System class static method:

arraycopy(Object src, int src_position,
          Object dst, int dst_position, int length)

where src is the array to be copied, dst is the destination array (of same type). The copy begins from src_position and starts in destination at dst_position for length number of elements.

Multi-dimensional Arrays

In Java, multi-dimensional arrays are arrays of arrays. That is, each element is a reference to an array object. For example, we could declare a two dimensional array as follows

 String [][] str = new String[3][2];

This is equivalent to

  String [][] str = new String[3][];

  str[0] = new String[2];
  str[1] = new String[2];
  str[2] = new String[2];

However, we don't need to keep the string array lengths the same. For example, this will also work:

  str[0] = new String[2];
  str[1] = new String[3];
  str[2] = new String[4];

The three 1-D arrays referenced by the three elements of the str array can reside in completely different areas in memory.

Elements are referenced by the brackets as usual. The JVM will check that the indices stay within the limits of each array.

In this example,

 str[0] = new String[]{"alice", "bob"};
 str[1] = new String[]{"cathy","don","ed"};
 str[2] = new String[]{"fay", "grant", "hedwig", "ward"};


 System.out.println("str[1][2] + str[2][3] = " + str[1][2] + str[2][3] );

we use the technique of initializing the values in the declaration with values between the braces. The print statement would print out

   str[1][2] + str[2][3] = edward

More about Arrays as Classes

As we mentioned earlier, arrays in Java are objects. An array inherits Object and possesses an accessible property - length - which provides the number of elements in the array.

For example, if a method uses Object as an argument, as in

    void aMethod(Object obj)
    { ... }

then an array can be passed in the argument since it is a subclass of Object:

   ...
   int [] iArray = new int[10];
   aMethod(iArray);
   ...

To make arrays appear in a convenient and familiar form (as in C, for example), the language designers provided brackets as the means of accessing the array elements. Without brackets, an array class would provide an element with a method something like the following:.

   String str_a = strArray.getElement(1);

instead of

      String str_a = strArray[1];

Arrays are thus somewhat more complicated in Java than in other languages but the class structure also provides some benefits. For example, the array checks the element number and if the element exceeds the declared length of the array, an out of bounds run-time exception will be thrown.

So unlike in C or C++, a program cannot go outside the array area and write to areas of memory where it should not. This avoids a very common program bug (and hack technique) that can be very difficult to track down since it may not show up till much later after the write occurred.

On the other hand, there is some performance penalty in the bounds checking that can slow down the speed of intensive processing with arrays.

Modified: May 22, 2008

            Tech
MoreComplexClass
ImprovedHistogram
JavaRandomNums
Vectors & Matrices
Exercises

           Physics
Runge-Kutta 2nd
  Demo 1
Runge-Kutta 4th
  Demo 2
BoundaryVal.Prob
Shooting Method
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.