3. One Dimensional Array
♣Structured collection of components.
♣Structure given a single name.
♣Individual elements accessed by index indicating
relative position in collection.
♣Type of elements stored in an array can be “just
about” anything.
♣Index of an array must be an integer.
4. Declaring Arrays
¤ Declaration examples:
int[] counts;
double[] scores;
String[] studentNames;
¤Syntax:
Data type Array name [constant]
5. Array Allocation
Arrays are allocated using the Java new operator
The syntax is:
new type[size];
Examples:
counts = new int[10];
scores = new double[15];
studentNames = new String[10];
6. Array Organization
counts
Each box is an int variable
The numbers on top are each variable’s
subscript or index
An array of size 10 has subscripts 0 to 9
0 1 2 3 4 5 6 7 8 9
7. Array Initialization
• Arrays can be initialized by giving a list of their elements
• If your list contains n elements the subscripts will range
from 0 to n – 1
• Do not need to allocate the array explicitly after it is
initialized
• Example:
int [] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
8. Arrays of Objects
•Arrays of objects are declared in the same manner
as arrays of primitive variables
•Assuming that a class Student was declared
elsewhere a client application could declare and
allocate an array of 10 students using
Student[ ] students;
students = new Student[10];