Java Reference
In-Depth Information
The first statement stores 10 into list[3] , the second statement stores 35 into list[6] ,
and the third statement adds the contents of list[3] and list[6] and stores the result
into list[5] (see Figure 9-5).
[0]
[1] [2]
0
[3] [4] [5]
45
[6]
0
[7]
[8]
[9]
list
0
10
0
35
0
0
0
0
0
FIGURE 9-5 Array list after the execution of the statements list[3]= 10; , list[6]= 35; ,
and list[5] = list[3] + list[6];
EXAMPLE 9-2
You can also declare arrays as follows:
final int ARRAY_SIZE = 10;
int [] list = new int [ARRAY_SIZE];
That is, you can first declare a named constant of an integral type, such as int , and then
use the value of the named constant to specify the size of the array.
9
Specifying Array Size during Program Execution
When you include a statement in a program to instantiate an array object, it is not
necessary to know the size of the array at compile time. During program execution, you
can first prompt the user to specify the size of the array and then instantiate the object.
The following statements illustrate this concept (suppose that console is a Scanner
object initialized to the standard input device):
int arraySize;
//Line 1
System.out.print("Enter the size of the array: ");
//Line 2
arraySize = console.nextInt();
//Line 3
System.out.println();
//Line 4
int [] list = new int [arraySize];
//Line 5
The statement in Line 2 asks the user to enter the size of the array when the program
executes. The statement in Line 3 inputs the size of the array into arraySize .
During program execution, the system uses the value of the variable arraySize to
instantiate the object list . For example, if the value of arraySize is 15 , list is an
array of size 15 .
 
 
Search WWH ::




Custom Search