These notes recap Topic 4.3. Full explanations and worked examples are in the study guide.
Recap
- An array stores multiple values of the same type: primitives or object references.
- The length is fixed at creation and is read with the
lengthattribute (no parentheses). newsets every element to a default:0,0.0,falseornull.- An initializer list such as
{72, 65, 90}creates and fills an array in one statement. - Square brackets read or assign an element using an index.
- Valid indices are 0 through
length - 1. Outside that range, the program throwsArrayIndexOutOfBoundsExceptionat run time.
Key relationships
| Task | Code |
|---|---|
| Create with defaults | int[] counts = new int[4]; |
| Create with values | int[] scores = {72, 65, 90, 58, 81}; |
| Number of elements | scores.length |
| First element | scores[0] |
| Last element | scores[scores.length - 1] |
| Assign | scores[1] = 70; |
| Computed index | w[w[0]] = 8; evaluates the inner w[0] first |
Default values
| Element type | Default |
|---|---|
int |
0 |
double |
0.0 |
boolean |
false |
String (any reference type) |
null |
Worked reminder
int[] w = new int[5]; w[0] = 3; w[1] = w[0] * 2; w[w[0]] = 8; leaves [3, 6, 0, 8, 0], because w[w[0]] is w[3]. For scores = {72, 65, 90, 58, 81}, scores.length is 5 and scores[5] throws ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. Swapping needs a temporary: int temp = v[0]; v[0] = v[2]; v[2] = temp;.
Tracing arrays in the exam
Draw the array as a row of boxes with the indices underneath. Update the boxes as each assignment runs. When an index is itself an array element, evaluate the inner one first. Before you answer, check every index against 0 to length - 1: if one is outside, the answer is the exception, not a value.
Compile and run-time errors
| Message or exception | Cause |
|---|---|
cannot find symbol ... method length() |
Writing scores.length() for an array |
incompatible types: int cannot be converted to String |
Storing an int in a String[] |
incompatible types: possible lossy conversion from double to int |
Using a double as an index or length |
ArrayIndexOutOfBoundsException (run time) |
An index below 0 or at least length |
Mistakes to avoid
- Using
lengthas the last index. - Writing
length()for an array. - Expecting
nullStrings to behave like"". - Assuming
b = acopies an array. - Forgetting a temporary variable when swapping.
Quick self-check
- What is the default value of a
booleanarray element? Answer:false. - For
int[] a = new int[8];, what are the valid indices? Answer: 0 to 7. - After
int[] x = {5, 6, 7}; x[x[0] - 3] = 1;, what isx[2]? Answer: 1, becausex[0] - 3is 2. - What does
new String[2]contain? Answer: twonullelements.