Burger Cse205 Note Arrays 01
Burger Cse205 Note Arrays 01
where T is the data type of each element of the array, name is the name of the array variable being
declared, and length is the number of elements in the array. length may be an integer literal, an
integer constant, an integer variable, or an expression that evaluates to an integer. Examples,
static final int L = 100;
int x = 10;
// a is an array of 5 ints (5 is an integer literal).
int[] a = new int[5];
// b is an array of 10 doubles (x is an integer variable).
double[] b = new double[x];
// c is an array of 100 String objects (L is an integer constant).
String[] c = new String[L];
// d is an array of 19 booleans (2 * x - 1 is an arithmetic expression that
// evaluates to an integer.
boolean[] d = new boolean[2 * x - 1];
CSE205 Object Oriented Programming and Data Structures Page 2
Note that we do not use the new operator when declaring and initializing an array at the same time.
CSE205 Object Oriented Programming and Data Structures Page 3
Because this is such a common operation we can also do this using the enhanced for loop. The
syntax is:
for (T value : arrayname) {
statements
}
where T is the data type of the elements of the array arrayname. During the first pass of the loop
value will be arrayname[0], on the second pass it will be arrayname[1], on the third pass it will be
arrayname[2], and so on until the final pass when value will be arrayname[arrayname.length].