Arrays
“An array is a fixed-length sequence of values of the same type, which can be an object type or a primitive type” (Horstmann, 2002, p. 530). Each value is stored in an element of the array, and each element is identified by its index: an integer which is the element’s sequence number.
Array elements are numbered from 0. For example: an array of 10 elements has indexes which run from 0 through 9. In general: the last element of an array is at length - 1.
An array is an object, and every array object knows its length: the number of elements which can be stored within it. The length of an array is stored in a public field called length and can be accessed with the dot operator.
To summarize: arrays
- are objects
- know their length via a public field: length
- contain elements numbered from 0
- contain elements all of the same type
- may contain elements whose type is also an array
Initialization
Each element of an array is automatically initialized upon its creation to
- 0, for numeric elements
- false, for boolean elements
- '\u0000', for char elements
- null, for object elements
/* * Example 1: * * Declare object reference and create array * with explicit size, then initialize. */ int[] validYear = new int[3]; … validYear[0] = 2000; validYear[1] = 2001; validYear[2] = 2002;
/*
 * Example 2:
 *
 * Declare object reference then create array and
 * initialize simultaneously. Size of array is
 * calculated by compiler.
 */
String[] vitamin = {"chocolate", "sugar", "caffeine"};
// Every array knows its length.
System.out.println(vitamin.length);
/* * Example 3: * * Declare object reference first; * create array and initialize later. */ int[] validYear; … validYear = new int[3]; validYear[0] = 2000; validYear[1] = 2001; validYear[2] = 2002;
/* Example 4:
 *
 * Declare object reference first;
 * create array and initialize later.
 */
char[] grade;
…
grade = new char[] {'A', 'B', 'C', 'D', 'F'};
Reference
Horstmann, C.S. (2002). Big Java. John Wiley & Sons, Inc. ISBN 0-471-40248-6.
touque.ca > Education Commons > Java > Resources > Data
[This page last updated 2020-12-23 at 12h13 Toronto local time.]

© 2007–2025 Hersch, Bear & Company Limited. All rights reserved. “Grammar Authority,” “grammarauthority.com,” “touque.ca,” and “Canada’s Thinking Cap” are trademarks of Hersch, Bear & Company Limited. All other trademarks and copyrights are the property of their respective owners.
Privacy Policy | Licence to Copy | How to cite | Contact us
