Java Reference
In-Depth Information
Arrays
At this point, you have dealt with only a few variables in each Java program. In some
cases, it's manageable to use individual variables to store information, but what if you
had 20 items of related information to track? You could create 20 different variables and
set up their initial values, but that approach becomes progressively more cumbersome as
you deal with larger amounts of information. What if there were 100 items, or even
1,000?
Arrays are a way to store a list of items that have the same primitive data type, the same
class, or a common parent class. Each item on the list goes into its own numbered slot so
that you can easily access the information.
Arrays can contain any type of information that is stored in a variable, but after the array
is created, you can use it for that information type only. For example, you can have an
array of integers, an array of String objects, or an array of arrays, but you can't have an
array that contains both String objects and integers.
Java implements arrays differently than some other languages do—as objects treated like
other objects.
To create an array in Java, you must do the following:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store information in that array.
Declaring Array Variables
The first step in array creation is to declare a variable that will hold the array. Array vari-
ables indicate the object or data type that the array will hold and the name of the array.
To differentiate from regular variable declarations, a pair of empty brackets ( [] ) is added
to the object or data type, or to the variable name.
The following statements are examples of array variable declarations:
String[] requests;
Point[] targets;
float[] donations;
You also can declare an array by putting the brackets after the variable name instead of
the information type, as in the following statements:
String requests[];
Point targets[];
float donations[];
 
Search WWH ::




Custom Search