Arrays
An array is a list of similar things
An array has a fixed:
Name
Type
Length
These must be declared when the array is created. qArrays sizes cannot be changed during the execution of the code
An array has a fixed:
Name
Type
Length
These must be declared when the array is created. qArrays sizes cannot be changed during the execution of the code
Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
Assigning Values
Refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
Can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
Can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Iteration Arrays
for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length; i++)
{
System.out.println(myArray[i]);
}
for (int i = 0; i < myArray.length; i++)
{
System.out.println(myArray[i]);
}
An Array has a fixed length
int a[]=new int[3];
a=new int[5];
a=new int[5];
Array of Objects
1. Declare the array
Student studentList[];
this declares studentList
2 .Create the array
studentList = new Student[10];
this sets up 10 spaces in memory that can hold references to Student objects
3. Create Student objects and add them to the array: studentList[0] = new Student("Cathy", "Computing");
Student studentList[];
this declares studentList
2 .Create the array
studentList = new Student[10];
this sets up 10 spaces in memory that can hold references to Student objects
3. Create Student objects and add them to the array: studentList[0] = new Student("Cathy", "Computing");