Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Arrays
Need to store a number of variables of the same type of data?
Use an array.
-
To declare an array, use the array type, and then [].
-
The [] can either go after the type, or after the name of the array.
-
When initializing an array to a value, put the type on the right hand side
of the =, followed by [] with the number of elements between the [ and
the ].
-
Example:
-
To declare an array of Strings: String[] names; or String
names[];
-
To initialize this array: names = new String[34];
-
To initialize and declare in one step: String[] names = new
String[34];
-
Note: The size that you declare in the array cannot change! If you
need an array that will dynamically grow, you have options, but they are
a bit slower. You can use a Vector, an ArrayList, or a LinkedList.
We'll cover those later.
-
To access an individual value in an array, use the index number of that
value. Keep in mind, Arrays start counting at 0!
-
names[0] = "Lee Way"; would assign "Lee Way" to the first element
of the array.
-
myName = names[0]; would store the value of the first element
of the names array in the variable myName.
More About Arrays


Created by: Brandan
Jones January 4, 2002