Array Creation and Access
Skill 2.BSkill 3.B
Big idea: An array is a fixed-size row of numbered slots, all the same type. Index 0 is the first slot and length - 1 is the last.
- Develop code used to represent collections of related data using one-dimensional (1D) array objects.
Two ways to create an array
Codeint[] scores = new int[4]; // 4 slots, all 0
String[] names = {"Ana", "Bo", "Cy"}; // initializer list
scores[0] = 90;
scores[3] = 75;
System.out.println(scores[0] + " " + scores[1] + " " + scores[3]);
System.out.println(names.length + " " + names[2]);Output90 0 75 3 Cy
Default values
new fills every slot with a default: 0, 0.0, false, or null for references. An array of objects starts full of null; you have to create each object.
double[] d = new double[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
System.out.println(d[0] + " " + b[1] + " " + s[0]);Output0.0 false nullBounds
Valid indexes are 0 to length - 1. Anything else throws an ArrayIndexOutOfBoundsException. The length can't change after creation.
int[] a = {3, 6, 9};
System.out.println(a[a.length - 1]);
System.out.println(a[a.length]);Output9 throws ArrayIndexOutOfBoundsException
Arrays are objects
An array variable holds a reference. Assigning one array variable to another makes them aliases of the same array.
Codeint[] a = {1, 2, 3};
int[] b = a;
b[0] = 50;
System.out.println(a[0]);Output50- An array holds a fixed number of values of one type (primitives or references).
- Length is fixed at creation and read with
length(no parentheses). newfills elements with defaults: 0, 0.0, false, or null.- An initializer list creates and fills an array at once.
- Valid indexes: 0 to
length - 1; otherwiseArrayIndexOutOfBoundsException.
- Arrays use
.length, Strings use.length(), ArrayLists use.size(). new Dog[5]creates 5 null references, not 5 Dogs.
int[] arr = new int[5]; What are arr.length and arr[4]?
Show answer
5 and 0.