4 min read
Arrays
Prerequisites: Loops
An array holds a fixed number of values of the same type, indexed
from 0.
int[] scores = {90, 85, 77};
System.out.println(scores[0]); // 90
System.out.println(scores.length); // 3 (a field, not a method)
scores[1] = 88;
Common mistakes
- Calling
scores.length()like a method — for arrays,lengthis a field with no parentheses (String's.length()is a method — the two are easy to mix up). - Accessing an index equal to or beyond
length— throwsArrayIndexOutOfBoundsExceptionimmediately, with no silentundefined-style fallback. - Needing to grow or shrink a collection — arrays are fixed-size; use
an
ArrayListinstead (see Collections Basics below).