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 incrmentation 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.

Last modified: Sunday, 20 September 2015, 07:21 PM