Previous
Index

Next


Chapter 4 Arrays collections & I/O

4.1) What are arrays?

Arrays are a standard structure for most programming languages. Thus they are supported by Visual Basic, Perl, PHP, C/C++ and many many other languages. If you cast your mind back to the very first example, the method main had the form

public static void main(String argv[]);

The part between the braces that says

String arg[]

Indicates that the method takes a parameter of a String array. This means that when the program starts running anything typed onto the command line after the program name will be contained within this String array. An array is a holder for multiple instances of a data type. So if you run your program with the command

java build one two three

The array arg will contain the string values

"one" "two" and "three"

You can extract any of the values from the array using the square bracket notation. Thus if you wanted to print out the second String value contained within the argv array you could use

System.out.println(argv[1]);

Note that accessing the second value means using 1 and not 2. This is because almost all counting in Java starts from zero and not one. Although you can make an argument that this is perfectly logical, it is something that can constantly mislead you.

The alternative to using an array or some method of holding multiple variables would be to create multiple variables for each value. So for the previous example you might create variables in the form

String sArg1;
String sArg2;
String sArg3;

Which is much less elegant than having a way of carrying round multiple values within one Array variable.

You can also find out how many elements an array has using it's length method. Thus you could retrieve the number of command line parameters thus

System.out.println(argv[].length);

Note that the elements of an array are always initialized to default values wherever the array is created. This is in contrast to primitives, which are given default values when created at class level but not as method variables.

Creating your own arrays

You will generally create your own arrays rather than take them from the command line. The syntax for this is as follows

int income[] = new int[12];

Note how you can now assign or set the values contained in the twelve slots in this array, send the array to some other part of the program and retrieve those values. You might for instance be writing an accounting program and use this array to store the income for each of the 12 months of the year.

You can assign values to each element by using square brackets to point to each element in turn. Thus

int income[] = new int[12];
income[0]=2;
income[1]=99;
income[2]=12;
income[3]=100;

A typical way of getting at the values within the elements of an array is with a for loop controlled by the length field of the array. Thus

for(int i=0; i < income.length; i++){
        System.out.println(income[i]);
}

The value of i has 1 added to it each time around the loop. Remember that ++ increments a number by one. It would be perfectly correct to code it with i=i+1 like this.

for(int i=0; i <3; i=i+1){

But this is not the standard Java idiom for doing this, so avoid this approach if you want to hold your head up amongst Java programmers. Incrementing the value of i means that income[i] points to the next element of the income array.

You could also use the other types of loops for accessing each element of the array, such as the while or do/while loops. Thus you could create a counter outside the loop, increment the counter each time around the loop and control the number of times around the loop with the counter. Here is an example of how you could do that.

public class MyAr{
    public static void main(String argv[]){
        MyAr m = new MyAr();
        m.go();
    }
    public void go(){
        int income[] = new int[3];
        income[0]=1;
        income[1]=22;
        income[2]=99;
        int i=0;
        while(i < income.length){
            System.out.println(income[i]);
            i++;
        }
    }

Many programmers prefer to use the for loop for this type of task, as the counter variable is limited in scope to the actual loop and the whole thing can be set up on one line. If you use a while/do while loop as in this example it is easy to forget to include the incrementation line (the i++), exactly as I did whilst creating that example.

Here is an example using the for loop.

public class Income{
    public static void main(String argv[]){
        Income i = new Income();
        i.go();
    }
    public void go(){
        int income[] = new int[12];
        income[0]=2;
        income[1]=99;
        income[2]=12;
        income[3]=100;
        for(int i=0; i < income.length; i++){
            System.out.println(income[i]);
        }


    }
}

Note that although the income array has 12 elements, the program only assigns values to 4 of the elements. When the program runs you will see it output the four assigned values as expected followed by another 8 zeros. This shows that the elements of an array get default values if you don't assign any values for yourself.

Assigning array values on creation

It is useful to assign values to arrays at the time of creation. For example if you were creating an array of Strings to represents the days of the week, it would be useful to assign the String values at creation time. The following example shows how you can do this.

public class Days{
    static String[] saDays = {"mon","tue","wed","thu","fri"};
    public static void main(String argv[]){
        System.out.println(saDays[0]);
    }
}

Note that this only creates elements for the weekdays, if you were to attempt to access elements 6 or 7 in the expectation of retrieving "sat" and "sun" the program would show an error message. This is known as "Throwing an exception" in Java jargon.

The new for loop

JDK1.5 (Java 5) introduced a new more compact version of the for loop. Thus the code in the previous example can be expressed as

public class NewFor{
static int income[] = new int[]{1,2,3,4};
	public static void main(String argv[]){
	for(int i : income){
		System.out.println(i);
	}	
}

Note how this form of the for loop does not require explicit coding of the increment counter and how it automatically steps through each element of the arrays.

The Limitations of Arrays

Arrays are extremely useful and are widely used in Java programs. They have limitations however. You need to know how many elements they will contain when you create them and every element must be of the same type. Thus you cannot create an array that stores an number for Salary and two Strings for first and last name. When a program is running you may not know how many elements are going to be needed. You can use a variable to control how many elements are created, but if you subsequently find your array needs to be bigger you are stuck with the original size. If you want to store multiple element of different types in one named storage unit, you can use the classes based on the Java Collections interface.




Previous
Index

Next