Java Reference
In-Depth Information
This program works fine. However, to read 100 (or more) numbers and print them
in reverse order, you would have to declare 100 or more variables and write many input
and output statements. Thus, for large amounts of data, this type of program is not desirable.
Note the following in the preceding program:
1. Five variables must be declared because the numbers are to be printed in
reverse order.
2. All variables are of type int —that is, of the same data type.
3. The way in which these variables are declared indicates that the variables
to store these numbers have the same name except for the last character,
which is a number.
From 1, it follows that you have to declare five variables. From 3, it follows that it would
be convenient if you could somehow put the last character, which is a number, into a
counter variable and use one for loop to count from 0 to 4 for reading, and use another
for loop to count from 4 to 0 for printing. Finally, because all the variables are of the
same type, you should be able to specify how many variables must be declared—as well as
their data type—with a simpler statement than the one used previously.
The data structure that lets you do all of these things in Java is called an array.
Arrays
An array is a collection (sequence) of a fixed number of variables called elements or
components, wherein all the elements are of the same data type. A one-dimensional
array is an array in which the elements are arranged in a list form. The remainder of this
section discusses one-dimensional arrays. Arrays of two or more dimensions are discussed
later in this chapter.
The general form to declare a one-dimensional array is:
9
dataType[] arrayName;
//Line 1
where dataType is the element type.
InJava,anarrayisanobject,justliketheobjectsdiscussedinChapter8.Becauseanarrayisan
object, arrayName is a reference variable. Therefore, the preceding statement only declares a
reference variable. Before we can store the data, we must instantiate the array object.
The general syntax to instantiate an array object is:
arrayName = new dataType[intExp];
//Line 2
 
 
Search WWH ::




Custom Search