next up previous contents
Next: Final note Up: Compound statements Previous: Strings   Contents

Arrays

Like strings, arrays are objects in Java. A typical declaration looks like this:

  int[] a;
  a = new int[100];

This can also be done as follows (a bit more C like);

  int a[];
  a = new int[100];

However, arguably the first definition is clearer in that it clearly declares a to be of type int[] and not int.

These two lines can be combined as:

  int[] a = new int[100];

Observe however, that declaring an array is fundamentally a two step process -- you declare that a is an array (without specifying its size) and then create the array with a fixed size at run time. Of course, you can abandon the current array and create a new one with a fresh call to new, as follows. (This example also shows that you can genuinely assign the size of the array at run time.)

  public class arraycheck{

    public static void main(String[] argv){

      int[] a;
      int i;
      int n;

      n = 10;

      a = new int[n];

      for (i = 0; i < n; i++){
          a[i] = i;
      }

      n = 20;

      a = new int[n];

      for (i = 0; i < n; i++){
          a[i] = -i;
      }

      for (i = 0; i < n; i++){
          System.out.print(i);
          System.out.print(":");
          System.out.println(a[i]);
      }
    }
  }

A very useful feature of arrays in Java is that the length of an array is always available: the length of an array a is given by a.length. A method such as a sort program that manipulates an array does not require an additional argument stating the length of the array to be manipulated, unlike in C.


next up previous contents
Next: Final note Up: Compound statements Previous: Strings   Contents
Madhavan Mukund 2004-04-29