Creating and Using Arrays
Creating and Using Arrays
This domain tests declaration, instantiation, initialization, indexing, and multidimensional arrays. Arrays are fixed-size objects, and most exam errors are compile-time declaration mistakes or runtime bounds/null failures.
Declarations and creation
int[] a;andint a[];both declare an array reference; neither allocates an array, and no size may appear in the declaration brackets.new int[3]allocates three elements with default values:0,false, ornull.- An initializer may appear only with a declaration or an array creation expression:
int[] a = {1,2};orint[] b = new int[]{1,2};. lengthis a field, not a method. Valid indexes are0throughlength - 1; outside that range throwsArrayIndexOutOfBoundsException.- Multidimensional arrays are arrays of arrays and may be ragged.
new int[2][]creates two null row references; each row must be allocated separately.
Worked example
int[] nums = {3, 1, 2};
int[] alias = nums;
alias[0] = 9;
System.out.println(nums[0]);
Both variables refer to the same array object, so the update through alias is visible through nums; the output is 9. Passing an array to a method works the same way: the method receives a copy of the reference.
Traps
a.length()does not exist for arrays; usea.length.- Accessing
a[a.length]is always out of bounds. - A
String[]is anObject[], but storing a non-String into it through anObject[]reference throwsArrayStoreException. - A jagged array element may be null; dereferencing it throws
NullPointerExceptionbefore any index check. - Reassigning a method parameter that holds an array does not change the caller's reference.