JRJC - How To Create and Access an Array

An array is an ordered list of data. A good example is to use an array to convert a numeric month to a string month. So referring to months[1] would give you "January". months[2] would give you "February".

Here is a program that would take a number and spit out the name of the month:


public class MonthName
{

    static String months[] =
    {
        null , "January" , "February" , "March" , "April", "May",
        "June", "July", "August", "September", "October",
        "November", "December"
    };

    public static void main( String[] args )
    {
        int m = Integer.parseInt( args[0] );
        System.out.println( months[ m ] );
    }

}

Suppose I type in

    java MonthName 1

args[0] pulls up the first parameter on the command line. In this case, it will be the string "1". The method Integer.parseInt() will convert the string "1" to the integer 1, which is stored in m.

months[ m ] will get the second string in the array months, which happens to be "January" at this time.

To demonstrate some other properties of arrays, I'm going to change the program a little:


public class MonthName
{

    static String months[];

    public static void main( String[] args )
    {
        months = new String[13];
        months[0] = null ;
        months[1] = "January";
        months[2] = "February";
        months[3] = "March";
        months[4] = "April";
        months[5] = "May";
        months[6] = "June";
        months[7] = "July";
        months[8] = "August";
        months[9] = "September";
        months[10] = "October";
        months[11] = "November";
        months[12] = "December";
        int m = Integer.parseInt( args[0] );
        System.out.println( months[ m ] );
    }

}

The program seems to work the same to the user, but internally it works much differently.

Instead of using a static initializer, I simply declare the variable months and leave it unitialized. At the beginning of main(), months is a null reference. If I were to attempt to access months as an array, I would get an exception. Inside of main() I initialize months to reference an array of 13 string objects (12 months plus the one null for month zero). I then assign each of the elements of the array.

For more information on arrays, see pages 109 to 120 in Just Java 1.2, or pages 185 to 199 in Just Java 2 (sixth edition).






For more information, please visit my java site.

And for a change of pace, you can visit my permaculture site.






© 2000 paul wheaton