Section 12b

One Dimensional Array Usage


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Setting Up Arrays and Using Them

The fundamental arrays in the Java programming language are simple to declare and define. You define the name of the array as you have done with variables before, and then you tell the computer how many cells or locations you want the array to have using the bracket operators. In Java, arrays are kind of like objects but not exactly. However, one requirement for creating (or instantiating) an array is that it will look almost like instantiating an object except you will ask the system for a specified quantity of values. Consider the following examples.

int[] integerArray = new int[ 10 ];
double[] doubleArray = new double[ 10 ];
char[] characterArray = new char[ 50 ];

Now the first thing you should notice is that literal numbers should not be used in a program, not even to define arrays. The above should really look like the following.

// in global constant area of class
private final int NUM_INTEGERS = 10;
private final int NUM_DOUBLES = 10;
private final int NUM_CHARACTERS = 50;

// declared at the beginning of a method
int[] integerArray = new int[ NUM_INTEGERS ];
double[] doubleArray = new double[ NUM_DOUBLES ];
char[] characterArray = new char[ NUM_CHARACTERS ];

The second thing you should notice is that you can declare Java arrays with variables. Not all programming languages allow this and only allow declaration of arrays with constants. This is the kind of thing you learn as you move around languages.

The result of your above definitions is as follows. In the case of the first example, an array named integerArray is created. Then, just like when you defined variables, a data storage "box", called an element (much like the "bucket" metaphor when you first learned about variables), is created. However, since you have indicated that you want ten of these integer data types, nine more "boxes" are created after the first one. If you define your array with ten in the brackets, you will have ten boxes available in which to store integer data types.

The array of "boxes" that you have created can be represented as shown below.

Example of initialized array

The array is shown with "stuff" in it when it is first created. The technical terminology for the stuff found in variables and arrays when they are first created is garbage, a term you have seen before. Some languages just allow garbage to be left in arrays when they are initialized but Java usually zeros them out if they are numerical, or places null (a standard constant meaning it references nothing, like void means a method returns nothing) in each element if it is an array of objects. That said, you should never a trust a language to conduct this action. First, you want to get in the habit of conducting your own initialization so you can move over to other languages, and second, sometimes "automatic" things in programming languages just don't work.

This is a good place to note the difference between the terms size or length, and the term capacity. An array may be declared with a capacity of 100 integers or doubles, etc., but until you actually place appropriate data in the array, the size or length is zero. Once you do place data into the array, the size or length is considered to be the number of valid items with which you are working, not the capacity of the array. You must be careful to maintain the distinction between these two quantities. It is not common to be using all of the elements in an array, so your array size or length will almost always be less than your array's capacity. As a note, the word size is commonly used to mean capacity in the Java language and in other programming. This is unfortunate since it blurs the difference but there are some things you have to learn to live with.

The following is an initialized array. For the moment, assume that the programmer took some action to implement the initialization, so your array will now look like the example shown below where all the values have been set to zero.

Example of array initialized to all zeroes

Always remember that arrays are not guaranteed to initialize themselves. It is possible later on when you are using classes, that they have the capacity to initialize themselves. However, for the safety of your programs, assume until otherwise told that your arrays start with garbage in them.

Whether your array has been initialized or not, once it is defined, you can store data in it. To implement this process, you need two things identified above. First, you need a location in which to place your data. The numerical value of an array location is called an index.

Secondly, you need the data itself. Since you have declared this particular array as an integer array, you are only allowed to store integers in it. In order to do this, you indicate the following to the computer, as shown here.

integerArray[ 5 ] = 49;

The above action has placed the value 49 in the sixth element of the array. Notice that since you placed it in the element labeled five, which is the offset from the first element, you have actually placed it in the sixth location. Your array of "boxes" would now look like the following.

Array example with sixth element set to 49

To get the value back, you basically invert the process. For example if you had defined an double value called rootValue, you could implement the following process.

double rootValue;

// get square root of array element
// method: sqrt
rootValue = Math.sqrt( integerArray[ 5 ] );

The library math method called sqrt that calculates (you guessed it) the square root of a value is used here. rootValue would be assigned the value seven because it is the square root of the value 49. Each element of the array acts just like an integer, or integer variable all its own. It is just easier to handle quantities of values by providing one name, and then using index locations to get the values back.

Remember that you can make an array of any data type, and hold values of that data type, as needed. The following provides some examples. The constant MAX_VALUES is used to define the number of elements. This is an abstraction because you may not always know what MAX_VALUES is. There is no harm in this because you can work with whatever number of elements are declared. Remember that as you study lists or groups of data, you may study lists of 10, 25, or 1,000 (or more) values.

However, to be a programmer, you must be able to manage a list of any number of items. For this reason, many times the number of items will be abstracted to N or n, as mentioned previously in this reference. Since N/n can represent any number of items, you can learn how to manage lists of any size. We commonly use N as the abstraction for "some number of values", but we always use self-documenting identifiers such as MAX_VALUES to declare our array capacities.

The following is a simple example of using an array of doubles.

// Example of array of doubles
double[] dArray = double[ MAX_VALUES ];

dArray[ 4 ] = 4.55;
dArray[ 6 ] = 3.77;
dArray[ 8 ] = dArray[ 4 ] * dArray[ 6 ];

// the ninth element in dArray now holds 17.1535

The following is a simple example of using an array of Booleans.

// Example of Boolean value array

bool[] bArray = new boolean[ MAX_VALUES ];
bArray[ 0 ] = true;
bArray[ 1 ] = true;
bArray[ 2 ] = false;

if( bArray[ 1 ] )
{
// output message
// method: printString, printEndline
conIO.printString( "The second element of bArray is true" );
conIO.printEndline
}

The following is a simple example of using a character array.

// Example of character array
char cArray[ MAX_VALUES ];

cArray[ 0 ] = 'a';
cArray[ 1 ] = 'b';
cArray[ 2 ] = 'c';
cArray[ 3 ] = 'd';
cArray[ 4 ] = 'e';
cArray[ 5 ] = 'f';

// output lunch message
// method: iostream <<
conIO.printString "I think I will eat at the " );
conIO.printEndline();
conIO.printString " " + cArray[ 2 ] );
conIO.printEndline();
conIO.printString " " + cArray[ 0 ] );
conIO.printEndline();
conIO.printString " " + cArray[ 5 ] );
conIO.printEndline();
conIO.printString " " + cArray[ 4 ] );
conIO.printEndline();

The result of the above character program segment is shown below.

I think I will eat at the c
a
f
e

Now that you have seen how to declare, assign to, and retrieve from an array, you have one condition left to consider. Array elements can be passed to methods exactly the same way as other variables; passing whole arrays is even easier but will require a little bit of discussion.

Start with passing array elements to a method. Suppose you have a method that adds two numbers together and returns their sum, called addEm, as shown here.

public int addEm( int valOne, int valTwo ) // header

Only the prototype is provided so you can see that it is just like any other method with normal parameters. So, when you need to add two values in an array, it works exactly as you might expect. Consider the following.

// usage
numbers[ 5 ] = 10;
numbers[ 15 ] = 20;

sum_1_2 = addEm( numbers[ 5 ], numbers[ 15 ] );
// sum_1_2 will now hold the value 30

Now for passing an array to a method, there is a little difference. The compiler needs to know that the identifier is an array instead of being a normal variable. You only need to add the two brackets to the end of the data type to indicate this. Consider the following method that adds all the values within the method and returns their sum.

public int addEmAllUp( int[] intArray, int sizeOfArray ) // header

And now consider how this is used.

// elsewhere in the program,
// some operation loads data into the array

// assume array is loaded with values
// after this operation
ages = loadDataToArray( size );

// call method with array and its size
// method: addEmAllUp
overallSum = addEmAllUp( ages, size );

Two important points from this example. First, with one minor exception discussed in a later topic, you will almost always pass the size along with the array to any method that will be using the array data. The method that loads the data needed to how many elements to load so the size variable was passed into it, as it was later passed into addEmAllUp. The Java array type has a length member value but again, this is insidious because the length member is not necessarily the size of the array (i.e., the number of valid items in it), it is the capacity of the array. Stay alert.

Secondly, note that ages looks like any other variable, and that is because it is like any other variable. It is just that ages – the reference – holds the address of the array and it doesn’t need brackets or anything else to make that happen. When you are passing a whole array to a method, you simply pass the name of the array.

Watch this video to see how to declare methods that will use arrays, and then observe how the arrays are used.

In this topic, you have seen arrays declared, you have seen array elements assigned values, you have seen values retrieved from array elements, and you have seen how to call methods with both array elements and whole arrays. The next topics will get into the actual use of arrays for the interesting things they can do.