Arrays

Single dimension arrays can be declared, as needed, anywhere in the program and initialized at the same time. The following program demonstrates how to set up an array of both strings and integers. The strings are initialized in the declaration and the integers are computed by cubing the index of each element.

Copy the following code into a text editor and
save it as array1.java.

class array1 {
public static void main (String args[]){
  String[] names =
{ "Harry", "John", "Alex", "Blake", "Scott"};
  int rnumbs[] = new int[5];
     for (int x=0 ; x<5 ; x++)
     {
      rnumbs[x] = x*x*x;
      System.out.println
(x +") " + names[x] + "  " + rnumbs[x]);
      }
  }
}

Line 3 sets up an array of strings and places the names
"Harry", "John", "Alex", "Blake", "Scott"
in the new array.
The next line declares a new array of 5 integers

The for loop places the cube of the index
in each
integer variable of the array

and finally the program prints the index, a ")" ,
the name and the cube of the index.

 

After compiling this program run it by typing

java array1

This program needs no command line parameters.
The output should resemble the following.

0) Harry  0
1) John  1
2) Alex  8
3) Blake  27
4) Scott  64

Notice that the array index starts at 0. This is consistent with command line parameters. They were contained in a special array - args[0] args[1] args[2]....

Go to the next topic: Multi-Dimensional Arrays.

Back to the Table of Contents