Array Creation and Access
| English | Chinese | Pinyin |
|---|---|---|
| initializer list | 初始化列表 | chū shǐ huà liè biǎo |
| ArrayIndexOutOfBoundsException | 数组下标越界异常 | shù zǔ xià biāo yuè jiè yì cháng |
Making an array
- Declare an array with a type and
[]:int[] scores; - Create it with
newand a size:int[] scores = new int[5];(five slots). - Or list the values directly:
int[] scores = {85, 90, 78};(an initializer list 初始化列表). - Every slot starts at the type's default (
0forint,nullfor objects).
Indexing from zero
- Array elements are numbered from
0; the last index islength - 1. - Access a slot with
scores[i]:scores[0]is the first,scores[2]the third. - Assign with
scores[0] = 100;and read withint x = scores[0];. - Off-by-one on the last index is the most common array bug.
The length field
- An array's size is its
lengthfield — no parentheses:scores.length. - (Contrast
String'slength()method, which has parentheses.) lengthis fixed once the array is created — arrays don't resize.- Use
scores.lengthin loop conditions to stay in bounds.
Out of bounds
- A valid index is
0tolength - 1; anything else throws an ArrayIndexOutOfBoundsException 数组下标越界异常. scores[5]on a length-5 array is out of bounds (indices are0–4).- The loop condition
i < scores.lengthkeepsiin range. - Never use
<=withlength— it steps one past the end.
Array size is length (a field, NO parentheses); String length is length() (a method, WITH parentheses). Mixing them up won't compile. And valid indices are 0 to length - 1 — scores[scores.length] is one past the end and throws an ArrayIndexOutOfBoundsException. Loop with i < scores.length, never i <= scores.length.
Creating and accessing an array:
int[] a = {10, 20, 30};— length3, indices0,1,2.a[0]is10;a[2]is30;a.lengthis3.a[3]throws ArrayIndexOutOfBoundsException (no index 3).
Create an array with new type[size] or an initializer list {...}. Elements are indexed from 0 to length - 1, accessed as a[i]. The size is the length field (no parentheses). An index outside 0..length-1 throws an ArrayIndexOutOfBoundsException — loop with i < a.length.
Indexing an array from 0
a[0]=10, a[1]=20, a[2]=30; a.length is 3.
For int[] a = {10, 20, 30}; what is a[0]?
Arrays are indexed from 0, so a[0] is the first element, 10.
How do you get the size of an array a?
Array size is the length FIELD (no parentheses).
For int[] a = {10, 20, 30}; what is a.length?
Three elements → length 3.
For a length-5 array, accessing index 5 (a[5])...
Valid indices are 0..4; index 5 is out of bounds.
String uses length() (a method) while an array uses length (a field).
Different syntax — parentheses for String, none for arrays.