Arrays
Site: | Saylor Academy |
Course: | CS101: Introduction to Computer Science I |
Book: | Arrays |
Printed by: | Guest user |
Date: | Wednesday, October 30, 2024, 7:31 PM |
Description
This chapter introduces arrays, a common multi-dimensional data structure used to store data of the same type. (Note that a class is a "data type" in this sense.) Arrays have some number of dimensions and a number of elements in each dimension. These are established when the array is created. The range of the array's index in each dimension goes from zero to the number of that dimension's elements minus one. A for loop is commonly used to initialize, manipulate, and access the values in an array. Here, we treat one-dimensional arrays, sometimes called vectors.
Table of contents
- 1. Arrays
- 2. Picture of an Array
- 3. Using Arrays
- 4. Arithmetic Expressions
- 5. Arrays are Objects
- 6. Bounds Checking
- 7. Array Initialization
- 8. Using a Variable as an Index
- 9. Using an Expression as an Index
- 10. More Complicated Example
- 11. Initializer Lists
- 12. Several Arrays per Program
- 13. Copying Values from Cell to Cell
- 14. Element Copied to any Cell
- 15. End of the Chapter
1. Arrays
Most real-world programs handle vast amounts of data. Fortunately, data usually can be organized and processed systematically. Arrays or similar structures are almost always used for this. When data is organized into arrays and processed in loops, a relatively small program can handle a vast amount of data. This chapter discusses arrays and shows examples of how they work.
Chapter Topics:
- The idea of arrays
- Array declaration
- Array declaration and construction
- Using arrays
- Automatic bounds checking
- Initializer lists
Question 1:
Say that you are writing a program that reads in 100 numbers. Would you like to declare 100 variables and write 100 input statements?
Source: Bradley Kjell, http://programmedlessons.org/Java9/chap60/ch60_01.html
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.
2. Picture of an Array
Answer:
Probably not. It would be useful to have an organized way of reading and storing the values.
Picture of an Array
An array is an object that is used to store a list of values.
An array is made out of a contiguous block of memory that is divided into a number of cells. Each cell holds a value, and all the values are of the same type. Sometimes the cells of an array are called slots. In the
example array pictured at right, each cell holds an int
.
The reference variable that points to this array is named data
. Sometimes the identifier "data
" is called "the name of the array" although it is really the name of a reference variable.
The cells are indexed 0 through 9. Each cell can be accessed by using its index. For example, data[0]
is the cell which is indexed by zero (which contains the value 23). data[5]
is the cell
which is indexed by 5 (which contains the value 14).
Facts:
- The cells are numbered sequentially starting at zero.
- If there are N cells in an array, the indexes will be 0 through N-1.
- The length of an array is the number of cells.
Sometimes the index is called a subscript. The expression data[5]
is usually pronounced "data-sub-five" as if it were an expression from mathematics: data5
.
The value stored in a cell of an array is sometimes called an element of the array. An array has a fixed number of cells. The values in the cells (the elements) can be changed.
An array is a full-blown object, and consists of more than just its cells. For example, the length
instance variable holds the number of cells of the array. For the above array, data.length
holds the
value 10.
Question 2:
What value is in data[7]
?
3. Using Arrays
Answer:
103
Using Arrays
Every
cell of an array holds a value of the same type. So, for example, you can have an array of int
s, an array of double
s, and so on.
You can have an array of object references. This is discussed in a later chapter.
The "before" array in the picture holds data of type int
. A cell of this array can be used anywhere a variable of type int
can be used. For example,
data[3] = 99 ;
works just like an assignment to an int
variable. After it has been executed, the array looks like the "after" array in the picture.
The value in cell 3 of the array has been changed.
Question 3:
What do you suppose is the value of the arithmetic expression:
data[2] + data[6]
4. Arithmetic Expressions
Answer:
23
data[2]
contains a 14 and data[6]
contains a 9, the sum is 23.
Arithmetic Expressions
An expression such as data[3]
is
called a subscripted variable.
A subscripted variable can be used anywhere an ordinary variable of the same type can be used. Since data[3]
contains an int
it can be used anywhere an int
variable may be used.
An arithmetic expression can contain a mix of literals, variables, and subscripted variables. For example, if x
contains a 10, then
(x + data[2]) / 4
evaluates to (10+14) / 4 == 6. Here are some other legal statements:
data[0] = (x + data[2]) / 4 ;
data[2] = data[2] + 1;
// increment the data in cell 3
x = data[3]++ ;
data[4] = data[1] / data[6];
Question 4:
Assume that the array holds values as in the picture. What will be the result of executing the statement:
data[0] = data[6] + 8;
5. Arrays are Objects
Answer:
The value 17 is put into cell 0 of data
.
Arrays are Objects
Array declarations look like this:
type[] arrayName;
This tells the compiler that arrayName contains a reference to an array containing type. However, the actual array object is not constructed by this declaration. The declaration merely declares a reference variable arrayName which, sometime in the future, is expected to refer to an array object.
Often an array is declared and constructed in one statement, like this:
type[] arrayName = new type[ length ];
This statement does two things: (1) It tells the compiler that arrayName will refer to an array containing cells of type. (2) It constructs an array object containing length in number of cells.
Here are some example array declarations:
double[] grades = new double[35];
// count is an int variable
short[] cost = new short[count];
char[] secretKey = new char[26];
// array ref. variable only
// no array object yet.
int[] future;
An array is an object, and like any other object in Java, it is constructed out of main storage as the program is running. The array constructor uses different syntax than other object constructors:
new type[ length ]
This names the type of data in each cell and the number of cells.
Once an array has been constructed, the number of cells it has does not change. Here is an example:
int[] data = new int[10];
This statement creates an array of 10 int
s, puts a zero into each cell, and puts a reference to that object in data
.
Question 5:
int[] data = new int[10];
- What is the length of the array
data
? - What are the indexes of
data
?
6. Bounds Checking
Answer:
int[] data = new int[10];
- What is the length of the array
data
? 10 - What are the indexes of
data
? 0, 1, 2, ..., 8, 9
Bounds Checking
Recall that:
The length of an array is how many cells it has. An array of length N has cells indexed 0..(N-1)
Indexes must be an integer type. It is OK to have spaces around the index of a subscripted variable, for example data[1]
and data[ 1 ]
are exactly the same as far as the compiler is concerned.
It is not legal to refer to a cell that does not exist.
Say that an array were declared:
int[] data = new int[10];
The table shows some subscripted variables of this array.
If your program contains an expression that is always illegal, it will not compile. But often the size of an array is not known to the compiler. The size of an array often is determined by data at run time. Since the array is constructed as the program is running, the compiler does not know its length and can't detect some errors.
As a Java program is running, each time an array index is used it is checked to be sure that it is OK. This is called bounds checking, and is extremely important for catching errors. If an executing program refers to a cell that does
not exist, an ArrayIndexOutOfBoundsException
is thrown, and (usually) the program is terminated. (See a future chapter for more on exceptions.)
Question 6:
Here is a declaration of another array:
double[] scores = new double[25];
Which of the following are legal?
7. Array Initialization
Answer:
int[] scores = new double[25];
scores[ 0 ]
OK scores[ 1 ]
OK scores[ -1 ]
illegal scores[ 10]
OK scores[ 25 ]
illegal scores[ 24 ]
OK scores[ 1.2]
illegal scores [2]
OK scores [ 4 ]
OK
Notice that there may be spaces between the reference variable name and the first bracket [ . Usually this is not done, however.
Array Initialization
Lacking any other information, the cells of an array are initialized to the default value for their type. Each cell of a numeric array is initialized to zero.
Each cell of an array of object references is initialized to null
. (Arrays of object references are discussed in an upcoming chapter.)
Of course, the program can assign values to cells after the array has been constructed. In the following, the array object is constructed and each cell is initialized to 0. Then some assignment statements explicitly change some cells:
class ArrayEg1 { public static void main ( String[] args ) { int[] stuff = new int[5]; stuff[0] = 23; stuff[1] = 38; stuff[2] = 7*2; System.out.println("stuff[0] has " + stuff[0] ); System.out.println("stuff[1] has " + stuff[1] ); System.out.println("stuff[2] has " + stuff[2] ); System.out.println("stuff[3] has " + stuff[3] ); System.out.println("stuff[4] has " + stuff[4] ); } } |
Question 7:
What does the program write?
8. Using a Variable as an Index
Answer:
stuff[0] has 23
stuff[1] has 38
stuff[2] has 14
stuff[3] has 0
stuff[4] has 0
Using a Variable as an Index
int values[] = new int[7]; int index; values[ 6 ] = 42; // literal index = 0; values[ index ] = 71; // put 71 into cell 0 index = 5; values[ index ] = 23; // put 23 into cell 5 index = 3; values[ 2+2 ] = values[ index-3 ]; // same as values[ 4 ] = values[ 0 ]; |
Question 8:
Given the above declarations, is the following legal?
index = 4;
values[ index+2 ] = values[ index-1 ];
9. Using an Expression as an Index
Answer:
Yes
Using an Expression as an Index
Using an expression for an array index is a very powerful tool. You often solve a problem by organizing the data into arrays, and then processing that data in a systematic way using variables as indexes. See the below program.
You can, of course, copy this program to your editor, save it and run it. Arrays can get confusing. Playing around with a simple program now will pay off later.
public class ArrayEg2 { public static void main ( String[] args ) { double[] val = new double[4]; // an array of double // cells initialized to 0.0 val[0] = 0.12; val[1] = 1.43; val[2] = 2.98; int j = 3; System.out.println( "cell 3: " + val[ j ] ); System.out.println( "cell 2: " + val[ j-1 ] ); j = j-2; System.out.println( "cell 1: " + val[ j ] ); } } |
Question 9:
What does the above program output?
10. More Complicated Example
Answer:
C:\users\default>java ArrayEg2
cell 3: 0.0
cell 2: 2.98
cell 1: 1.43
More Complicated Example
public class ArrayEg3 { public static void main ( String[] args ) { double[] val = new double[4]; val[0] = 1.5; val[1] = 10.0; val[2] = 15.5; int j = 3; val[j] = val[j-1] + val[j-2]; // same as val[3] = val[2] + val[1] System.out.println( "val[" + j + "] == " + val[j] ); } } |
Question 10:
What does the above program print out?
11. Initializer Lists
Answer:
val[3] == 25.5
Initializer Lists
You can declare, construct, and initialize the array all in one statement:
int[] data = {23, 38, 14, -3, 0, 14, 9, 103, 0, -56 };
This declares reference variable data
for an array of int
. Then it constructs an int
array of 10 cells (indexed 0..9) with the designated values into the cells. The first value in the initializer list corresponds to index 0, the second value corresponds to index 1, and so on. (So in this example, data[0]
gets the 23.) Finally it puts a reference to the array object in the variable data
.
You do not have to say how many cells the array has. The compiler will count the values in the initializer list and make that many cells. Once an array has been constructed, the number of cells does not change. Initializer lists are usually used only for small arrays.
The initializer has to be part of the declaration, as above. The following does not work.
int[] data;
// error
data = {23, 38, 14, -3, 0, 14, 9, 103, 0, -56 };
Question 11:
Write a declaration for an array of double
named dvals
that is initialized to contain 0.0, 0.5, 1.5, 2.0, and 2.5.
12. Several Arrays per Program
Answer:
double[] dvals = { 0.0, 0.5, 1.5, 2.0, 2.5 };
Several Arrays per Program
class ArrayEg4 { public static void main ( String[] args ) { int[] valA = { 12, 23, 45, 56 }; int[] valB = new int[4]; = ; = ; = ; = ; } } |
Question 12:
Fill in the blanks so that the values in valA
are copied into the corresponding cells of valB
.
13. Copying Values from Cell to Cell
Answer:
class ArrayEg4
{
public static void main ( String[] args )
{
int[] valA = { 12, 23, 45, 56 };
int[] valB = new int[4];
valB[ 0 ] = valA[ 0 ] ;
valB[ 1 ] = valA[ 1 ] ;
valB[ 2 ] = valA[ 2 ] ;
valB[ 3 ] = valA[ 3 ] ;
}
}
Copying Values from Cell to Cell
valB[ 0 ] = valA[ 0 ] ;
This is just like an assignment statement
spot = source;
where both variables are of primitive
type
int
. After the four assignment statements of the answer have executed, each array contains the same values in the same order:
Super Bug Alert: The following statement does not do the same thing:
valB = valA ;
Remember that arrays are objects. The statement above copies the object reference in valA
into the object reference variable valB
, resulting in two ways to access the array object valA
, as
seen in the second picture.
The object that valB
previously referenced is now lost (it has become garbage.)
valA
and valB
are now aliases for the same object.
The array object previously pointed to by valB
is now garbage (unless there is some other reference variable that points to it.)
Question 13:
Say that the following executes, resulting in the above picture. What is printed out?
valB = valA;
valA[2] = 999;
System.out.println( valA[2] + " " + valB[2] );
14. Element Copied to any Cell
Answer:
Since valA
and valB
both refer to the same object, valA[2]
and valB[2]
are two ways to refer to the same cell. The statements print out:
999 999
Element Copied to any Cell
Of course, the value in a cell of one array can be copied to any cell of another array if the type of the first array can be converted to the type of the second.
In the following, selected int
s from an array of int
s are copied to various cells in an array of double
s.
class ArrayEg5 { public static void main ( String[] args ) { int[] valA = { 12, 23, 45, 56 }; double[] valB = new double[6]; valB[ 0 ] = valA[ 2 ] ; valB[ 3 ] = valA[ 2 ] ; valB[ 1 ] = valA[ 1 ] ; valB[ 5 ] = valA[ 0 ] ; System.out.println( "valB:" + valB[0] + ", " + valB[1] + ", " + valB[2] + ", " + valB[3] + ", " + valB[4] + ", " + valB[5] ); } } |
Question 14:
Fill in the blanks in the following so that the elements in valA
are copied to valB
in reverse order:
class ArrayEg6
{
public static void main ( String[] args )
{
int[] valA = { 12, 23, 45, 56 };
int[] valB = new int[4];
= ;
= ;
= ;
= ;
}
}
15. End of the Chapter
Answer:
class ArrayEg4
{
public static void main ( String[] args )
{
int[] valA = { 12, 23, 45, 56 };
int[] valB = new int[4];
valB[ 0 ] = valA[ 3 ] ;
valB[ 1 ] = valA[ 2 ] ;
valB[ 2 ] = valA[ 1 ] ;
valB[ 3 ] = valA[ 0 ] ;
}
}
End of the Chapter
Here is a list of facts about arrays. You may wish to refer back to a page that discusses a particular fact in greater detail.
array An array is an object that has room for several values, all of the same type.
Each value is stored in a cell of the array. The values stored in an array are sometimes called the elements of the array.
If there are N cells in the array, the cells are indexed from 0 up to (N-1).
The index must be an integer value (byte, short, or int).
array, declaration An array declaration looks like:
int[] intArray;
This declaration declares the array reference
intArray
. It does not create the actual object.An array can be declared and constructed in a combined statement:
int[] intArray = new int[17];
This declaration declares the array reference
intArray
, and constructs an array object containing 17 cells that can hold int.When an array object is constructed using the
new
operator, the cells are array, default initialization initialized to the default value of the type of the cell. Numeric types are initialized to zero.Once an array object has been constructed, the number of cells it has can not be changed. (However, a completely new array object, with a different number of cells, can be constructed to replace the first array object.)
subscripted variable A subscripted variable such as
intArray[12]
can be used anywhere an ordinary variable of the same type can be used.The index used with an array can be stored in a variable, for example
int j = 5 ; intArray[ j ] = 24; // same as: intArray[ 5 ] = 24
The index used with an array can be computed in an expression, for example
int j = 5 ; intArray[ j*2 + 3 ] = 24; // same as: intArray[ 13 ] = 24
array, bounds checking The index used with an array must be within the range 0..(N-1) where N is the number of cells of the array.
If an index that is out of bounds is used with an array, an exception is thrown and the program stops running (unless it catches the exception.)
An array can be declared, constructed, and initialized using an array, initializer list. This can only be done when the array is first declared.
Arrays can be confusing at first. But they are very important. If you are somewhat uncertain about arrays, take a break. Then, sometime later, come back to this chapter and work through it again.