Google
 

 

up previous next contents
Up: 2. Day 2: The Previous: 2.3 Variables, constants, and Next: 2.5 Strings   Contents

2.4 Arrays

  • An array is a collection of variables of the same type.
  • A variable declared in brackets, [], is an array reference.
  • Three steps
    • Declaration - tell the compiler what the name is and the type of its elements.
    • Construction -
    • Initialization
      int numbers[];          // declaration
      numbers = new int[100]; // construction
      for (int i=0; i<100; i++)
      {
        numbers[i] = i;
      }
      
    String username[];
    float[] balance;
    
  • Components of an array are accessed by a simple integer index.
  • Element indexing begins with the number 0.
    username[0] = "Fred";
    username[1] = "Barney";
    
  • The size of an array is easily accessed with the length attribute.
    for (int i=0; i<username.length; i++)
    {
        System.out.println("The user's name is: " + username[i]);
    }
    
  • Indexing past the end of an array throws an exception.
  • Multidimensional arrays can be created.