Arrays
Introducing Arrays
Declaring Array Variables
Creating Arrays
Initializing Arrays
Passing Arrays to Methods
One dimensional Arrays
Two dimensional Arrays
Search and Sorting Methods
Introducing Arrays
Array is a data structure that represents a
collection of the same types of data.
double[] myList = new double[10];
myList reference myList[0]
myList[1]
myList[2] An Array of 10
myList[3] Elements
myList[4] of type double
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Declaring Array Variables
datatype[] arrayname;
Example:
double[] myList;
datatype arrayname[];
Example:
double myList[];
Creating Arrays
arrayName = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
Declaring and Creating
in One Step
datatype[] arrayname = new
datatype[arraySize];
double[] myList = new double[10];
datatypearrayname[] = new
datatype[arraySize];
double myList[] = new double[10];
The Length of Arrays
Once an array is created, its size is fixed.
It cannot be changed. You can find its size
using
[Link]
For example,
[Link] returns 10
Initializing Arrays
Using a loop:
for (int i = 0; i < [Link]; i++)
myList[i] = i;
Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one statement.
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;