6.1 Array Variables, Objects, and Elements
Prerequisites: Variables, Types, Conditions, and Loops
Estimated time: 20 minutes
You are ready to continue when: You can distinguish between array variables, array objects, and array elements, and handle empty arrays,
null, and invalid lengths
One int score stores one score. Declaring score2 through score1000 is not maintainable and cannot be processed uniformly by a loop. A Java array stores a fixed number of values with one component type in an object and accesses them by zero-based index.
1. Declaring Variables Is Not the Same as Creating an Array
int[] scores; // Declare a variable that can refer to an int array
scores = new int[5]; // Create a length-5 array and store its referenceIt can also be written together:
int[] scores = new int[5];There are three different concepts here:
| Name | Example | Meaning |
|---|---|---|
| Component Type | int | What type of data can each position hold |
| Array Type | int[] | Which type of array the variable can reference |
| Array Object | new int[5] | The five components created at runtime |
The variable scores stores a reference to an array, not the five integers themselves. An array is an object, but once created, its length is fixed. If you need a different length, you must create another array and copy the required elements.
The Java language defines indexing behavior but does not require programmers to rely on any specific physical layout of the object. You can think of indexing as an offset relative to the first element: the offset of the first element is 0, so valid indices for a length of 5 are 0, 1, 2, 3, and 4.
2. New Array Gets Default Values
int[] counts = new int[3];
boolean[] flags = new boolean[2];
String[] names = new String[2];
System.out.println(counts[0]); // 0
System.out.println(flags[0]); // false
System.out.println(names[0]); // nullArray components are initialized by default:
| Component Type | Default Value |
|---|---|
byte, short, int, long | 0 of the corresponding type |
float, double | Positive zero of the corresponding type |
char | \u0000 |
boolean | false |
| Reference Types | null |
This is different from local variables inside a method. Local variables must be explicitly assigned before they can be read; new arrays have their components initialized by the runtime.
3. Writing and Reading Must Be Done Through Legal Indices
int[] scores = new int[5];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 95;
scores[4] = 88;
System.out.println(scores[2]); // 78
System.out.println(scores.length); // 5length is a read-only field of an array, with no parentheses. For an array of length n, the index must satisfy:
0 <= index && index < nAccessing scores[-1] or scores[5] will throw ArrayIndexOutOfBoundsException. Java checks array access at runtime and does not automatically expand the array or write out-of-bounds accesses to other locations.
4. Initializers for a Small Number of Known Values
You can create and initialize an array at the time of declaration:
int[] scores = {85, 92, 78, 95, 88};When you need to replace the entire array after declaration, you must specify the array type:
int[] scores = new int[0];
scores = new int[]{60, 70, 80};The following is not compilable:
// scores = {60, 70, 80}; // Array initializer cannot be used alone on the right side of an assignmentYou also cannot include both the length and the initialization list in a single array creation expression:
// int[] scores = new int[3]{60, 70, 80}; // Compilation error5. Three States: Empty Array, null, and Invalid Length
int[] empty = new int[0];
System.out.println(empty.length); // 0
int[] missing = null;- An empty array is an existing object with a length of 0 and no valid indexes.
nullindicates that the variable currently does not reference an array; readingmissing.lengthwill throwNullPointerException.new int[-1]throwsNegativeArraySizeExceptionat runtime.
In API design, it is important to clearly distinguish between "no array provided" and "an array with no elements provided." If the two meanings are the same, it is typically preferable to receive the empty array, as the caller can more easily iterate directly over it.
6. Array Variable Assignment Creates Aliases
int[] first = {10, 20, 30};
int[] second = first;
second[0] = 99;
System.out.println(first[0]); // 99This does not create a second array. first and second store references to the same array object. Therefore, changes made through either variable are visible on both sides.
If you need a separate array, you must copy the components. A later lesson will compare clone, Arrays.copyOf, and System.arraycopy. For reference-type arrays, these operations still copy the references within the components, and do not automatically copy each individual object.
Language Difference Window
- C++ built-in arrays have a storage duration that depends on the declaration location and allocation method, and are not limited to "stack arrays" and "heap arrays" only. Modern C++ typically prefers
std::arrayfor fixed-length andstd::vectorfor dynamic-length. - Python commonly uses
list, which can grow and allows for mixed types; type annotations and engineering conventions can further constrain element types. It is not equivalent to Java arrays.
scores = [85, 92, 78, 95, 88]
print(scores[2]) # 78
scores.append(100)Professional Quick Reference
| Purpose | Java Syntax | Boundary |
|---|---|---|
| Declare a variable | int[] values; | Must be assigned before use |
| Create a fixed-length array | new int[5] | Length cannot be negative |
| Initialize with values | int[] values = {1, 2}; | Shorthand is only for declaration |
| Replace values later | values = new int[]{1, 2}; | Whether the original object is still referenced depends on aliasing |
| Read the length | values.length | values cannot be null |
| Access components | values[index] | 0 <= index < length |
Before Moving On
Mark int[] values, new int[5], and values[0] as array variables, array objects, and component access, respectively. Then explain how empty arrays, null, and negative lengths fail in terms of which phase and in what manner. Finally, draw the two variables and one array object after second = first.
Next, we’ll visit the elements with loops and check forward, reverse, and empty-array boundaries.
→ Next: Array Indexing and Traversal
Specification: JLS §10: Arrays.