Skip to content

VOL 01 / CH 06 / LESSON 01

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 ​

java
int[] scores;          // Declare a variable that can refer to an int array
scores = new int[5];   // Create a length-5 array and store its reference

It can also be written together:

java
int[] scores = new int[5];

There are three different concepts here:

NameExampleMeaning
Component TypeintWhat type of data can each position hold
Array Typeint[]Which type of array the variable can reference
Array Objectnew 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 ​

java
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]);  // null

Array components are initialized by default:

Component TypeDefault Value
byte, short, int, long0 of the corresponding type
float, doublePositive zero of the corresponding type
char\u0000
booleanfalse
Reference Typesnull

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.

java
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); // 5

length is a read-only field of an array, with no parentheses. For an array of length n, the index must satisfy:

text
0 <= index && index < n

Accessing 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:

java
int[] scores = {85, 92, 78, 95, 88};

When you need to replace the entire array after declaration, you must specify the array type:

java
int[] scores = new int[0];
scores = new int[]{60, 70, 80};

The following is not compilable:

java
// scores = {60, 70, 80}; // Array initializer cannot be used alone on the right side of an assignment

You also cannot include both the length and the initialization list in a single array creation expression:

java
// int[] scores = new int[3]{60, 70, 80}; // Compilation error

5. Three States: Empty Array, null, and Invalid Length ​

java
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.
  • null indicates that the variable currently does not reference an array; reading missing.length will throw NullPointerException.
  • new int[-1] throws NegativeArraySizeException at 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 ​

java
int[] first = {10, 20, 30};
int[] second = first;

second[0] = 99;
System.out.println(first[0]); // 99

This 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::array for fixed-length and std::vector for 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.
python
scores = [85, 92, 78, 95, 88]
print(scores[2])  # 78
scores.append(100)

Professional Quick Reference ​

PurposeJava SyntaxBoundary
Declare a variableint[] values;Must be assigned before use
Create a fixed-length arraynew int[5]Length cannot be negative
Initialize with valuesint[] values = {1, 2};Shorthand is only for declaration
Replace values latervalues = new int[]{1, 2};Whether the original object is still referenced depends on aliasing
Read the lengthvalues.lengthvalues cannot be null
Access componentsvalues[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.

Built with VitePress | Software Systems Atlas