Lesson 8.1 Introducing Arrays
In this section, you'll learn about Java's array variables. We'll focus on arrays of primitive types and learn about arrays of object types, "Object Arrays".
What Are Arrays?
Variables, you'll recall, are 'buckets' that hold a value. When you create the bucket, you have to say what kind of thing you're going to store in it; there are no "one size fits all" buckets.
When you want to store a lot of values, however, creating individual variables for each value can quickly become very tedious--especially if the values are similar and somehow related. A program that keeps the records for a class of Java students, for instance, would need to declare variables for each student, something like this:
|
Individual Variables
|
public class JOLS00
{
// Attributes
Student jol100 = new Student();
Student jol101 = new Student();
Student jol102 = new Student();
...
} |
The Array
An array is a collection variable; an array can hold multiple values rather than just a single value. An array can store values of any type--either primitive values or object references--but each of the values in a single array must all be of the same type.
When you create an array, you give the array a name, just like you would any other variable. You then access the individual values stored in the array--these are called the array elements--by specifying which of the values you want to access using an index or subscript. In Java, all array subscripts begin at zero.
|
Why Start at Zero?
|
| One of the perennial debates in programming language circles has to do with whether array elements should be numbered starting with zero or one. Java, like C and C++, uses zero-based arrays. While you might not like this, it may help a little if you understand why zero-based arrays are used.
If you think of the array subscript as the number of the element--# 1, # 2, etc...--then zero based arrays make no sense at all. After all, what does it mean to be the "zeroth" element?
In Java, array subscripts are not the number of the element; instead, the index is an offset from the beginning of the array. When you tell the compiler to retrieve myArray[5], you are telling it to go to the array named myArray, then skip five elements and bring you the element it finds there. If you tell it to access myArray[0], the compiler knows it doesn't have to skip any elements at all, and it brings you the first element. |
Array Variables
In Java, array variables are references, just like object variables. An array variable does not actually hold the individual values in the array, it refers to them. Thus, two array variables can point to the same actual array of values.
Here's an example. The array variable named gradeAR pictured here [click image to enlarge], is a char array variable. The variable gradeARrefers to a five-element array of char elements.
The individual elements in gradeAR are each indexed or subscripted starting at 0 and going to 4.
Creating Arrays
Creating an array variable is a two-step process, just like creating an object variable. When you create an object, you first declare an object variable,
and then "attach" an actual object to the object variable:
public void init()
{
kermit = new Frog("Kermie");
...
} |
Arrays work in an almost identical manner.
Step 1: Declare
To declare an array variable you specify:
- The type of elements you’ll store in the array. This can be any type, object or primitive.
- A name for the entire collection. Here you must follow the standard naming rules. There are no special names for arrays.
- A set of empty brackets [] following either the variable name or the type. Note that these are not parentheses. Java programmers tend to favor placing the brackets after the type name because it associates the brackets with the type rather than with the variable.
Declaration Examples
Here are a few examples to give you the idea.
- This creates an array variable that holds chars. We've put the brackets after the type name. You should read this as "gradeAR is an array of char".
- This creates an array variable that holds ints. Here we've put the brackets after the variable name. Read this as "pieces is an array of int".
- This creates an array variable that holds Elephants. As you can see, the syntax is just the same whether you're creating an array of primitive types or of object references.
Step 2: Create the Array
Just as with objects, the actual array is created by using the new operator. When used to create an array, the syntax used with new is a little different than the syntax used to create an object.
When creating an object, you use an object constructor which appears on the right side of the assignment operator. When creating an array, you use an array constructor. Here's the difference:
Object Constructors
An object constructor uses the name of the class, followed by parentheses and any arguments that are used by the object.
|
Object Constructors
|
public void init()
{
Button b;
b = new Button("Press Me");
Label l;
l = new Label("Hi", Label.RIGHT);
} |
Object constructors are actually methods defined inside the class of the object you are creating.
- A class may have several overloaded constructors, as the Label class does, for instance.
- You do not use a constructor to create primitive variables.
Array Constructors
An array constructor uses the name of the class or the name of a primitive type, followed by a set of brackets instead of parentheses.
|
Array Constructors
|
public void init()
{
int nTiles = 3;
char[] gradeAR;
gradeAR = new char[5];
int pieces[];
pieces = new int[nTiles * nTiles];
Elephant[] herd;
herd = new Elephant[100];
} |
Inside the brackets you put the number of elements you want your array to have. The number:
- Can be a constant, like the 5 used for gradeAR. The gradeAR array has five elements, and the subscripts go from zero to four.
- Can be an expression or variable, like the expression nTiles * nTiles, used for the pieces array. The pieces array has nine elements, and the subscripts go from zero to eight.
When you create an array that holds objects, such as herd, the array actually holds references to objects. You still have to create the object variables in a separate step. Lesson 8.5, "Object Arrays", covers the steps you need to follow to do this.
Array Initialization
If you like, you can declare an array variable and create the array at the same time. This is actually quite common. Here's what it looks like:
| double[] scores = new double[5]; |
When you first create an array using new, the values stored in each of the elements are set to:
- 0 if the array holds integer or character values.
- The value false if the array holds boolean values.
- The value null if the array holds object references.
Please note that this is different from simple variables. With a simple variable, default initialization is only provided if the variable is a field [declared outside of all methods]. All array variables, both fields and locals, are automatically initialized when you create them.
Often, however, this default initialization is not what you want. If this is the case, then you'll have to explicitly initialize your variables. You can initialize the elements in an array in two ways:
- You can explicitly set each element by using the subscripted name of each element and storing a value in that element. [This is often done in a loop.]
- You can provide a set of initial values in an initializer list.
Initializer Lists
To explicitly provide a set of initial values, you list each value, separated by commas, inside a set of braces. When you do this, you cannot supply a size for the array and you do not use the new operator.
Here's an example declaration that shows you how to do this:
char[] allGrades =
{'A', 'B', 'C', 'D', 'F', 'W', 'I'}; |
When you write this, the Java compiler counts the number of elements in your initializer and automatically creates a seven-element array. Make sure you don't forget the semicolon at the end of the list.
|
Java vs C/C++ Initialization
|
| If you're a C/C++ programmer, don't confuse the way that Java does things and the way that C does it. Java does not have partial array initialization, like C, where you can combine an explicit array size with a partial initialization list. |
You can also use a similar [although infrequently used] syntax, which employs both the intitializer list, and the new operator, to create array literals which can be assigned to array variables, like this:
int[] ar;
ar = new int[] { 1, 2, 3 }; |
This creates an anonymous array holding the values 1, 2, and 3, and assigns a reference to the variable ar.
Something to Talk About
Here are some problems to make sure that you've mastered the material in this section:
1. Create an array variable that refers to an array of three chars.
2. Create an array variable that can refer to any number of doubles.
3. Create an array of 1,000 doubles and assign it to the array variable in Question 2.
4. Create an array variable that can refer to any number of true/false values.
5. Create an initialized nine-element array that holds nine true/false values [your choice for the distribution], and assign it to the array variable in Question 4.
Please continue to the next section of this lesson.
|