- About
- Statistics
- Number Theory
- Java
- Data Structures
- Cornerstones
- Calculus
Suppose we want to write a program that computes the average midterm score of all the students and find out how many scored above the average. How many variables do we need for storing the scores? If we have 30 students in the class, then we would need at least 30 variables, right? Rather than declaring 30 variables, one by one, we can use a special data structure called an "array" to declare them all at once and work with them in a way that minimizes confusion.
An array is a data structure that represents an organized collection variables of the same type.
One-dimensional arrays can be thought of as a list of n variables numbered 0 through [n-1]. [Note: computer scientists and mathematicians, unlike the rest of the people on the planet, always start counting with zero -- weird huh?!]
Two-dimensional arrays frequently [but not always] behave like a n × m table of variables. Technically, they are just one-dimensional arrays whose variables are themselves one-dimensional arrays. We'll talk more about these in a bit -- but first...
Higher dimensional arrays can be created as well, being just arrays of arrays of arrays of... [and so on].
Declaring and Creating Arrays
To declare a one-dimensional array, we can use the syntax seen in either of the following, although the first is preferred:
Syntax:
datatype[] arrayRefVar; //This is the preferred way!
datatype arrayRefVar[]; //Although Java won't complain if you
//declare arrays like this
Examples:
double[] myFirstList; int mySecondList[];
The number of variables in your array determines the amount of memory that must be allocated to store that array -- and notice, the declaration doesn't say how big the array should be. So we have an additional step we must do before we can actually use the array -- we must tell the computer how many variables we wish to have in the array. This is called "creating" the array, and the syntax and an example are shown below:
Syntax:
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
We can declare and create an array in one step if we wish:
datatype[] arrayRefVar = new datatype[arraySize];
does the same thing as...
datatype[] arrayRefVar; arrayRefVar = new datatype[arraySize];
Example:
double[] myList = new double[10]; //declares and creates //an array of 10 doubles
When an array is created, its elements are assigned a default value that depends on the type of the elements contained in the array.
-
0
for the numeric primitive data types -
[char] 0
for the char types -
false
for boolean types null
for reference types
Assigning Values to Array Elements
The ith element in a one-dimensional array named myList can be referenced by myList[i]
.
As such, if we wished to declare and create an array that would
contain 10 doubles
and then assign values to some of the elements in such an array, it might look like this:
double[] myList = new double[10]; //