Getting Started
In programming, we often need to manage not just single pieces of data, but collections of related data—like a list of student grades, daily temperatures, or product prices. An array is Java's fundamental data structure for storing a fixed-size, sequential collection of elements, all of the same data type. This chapter covers how to create these arrays and how to access or modify the individual data elements they contain.
What You Should Be Able to Do
Declare an array reference variable and create an array of a specific size and type.
Understand that array elements are automatically initialized to default values (
0,0.0,false, ornull).Access an element at a specific position in an array using its index.
Assign a new value to an element at a specific position in an array.
Use the
.lengthproperty to determine the size of an array.Identify code that will cause an
ArrayIndexOutOfBoundsException.
Key Concepts & Java Implementation
The Core Idea
An array is an object that holds a fixed number of values of a single type. Think of it like a row of numbered mailboxes. The entire row is the "array," and each individual mailbox is an "element." Each mailbox has a unique number, called an index, that you use to access it.
There are three critical rules for arrays in Java:
Fixed Size: Once an array is created, its size cannot be changed. If you create an array for 10 integers, it will always have space for exactly 10 integers.
Homogeneous Type: All elements in an array must be of the same data type (e.g., all
int, alldouble, or allString).Zero-Based Indexing: The first element of an array is always at index
0, the second is at index1, and so on. The last element is at indexsize - 1.
Syntax & Implementation
Creating an Array
Creating an array is a two-step process: declaration and instantiation.
Declaration: You declare a variable that will refer to the array. This tells the compiler the variable's name and the type of data the array will hold.
Instantiation: You use the
newkeyword to create the array object in memory, specifying its size. This is when memory is allocated and elements are set to their default values.
These two steps can be done separately or on the same line.
- Syntax Table: Array Creation
| Syntax | Purpose | Java Example |
|---|---|---|
type[] arrayName; | Declaration: Creates a reference variable that can hold an array. | int[] scores; |
arrayName = new type[size]; | Instantiation: Creates the array in memory with a specific size. | scores = new int[10]; |
type[] arrayName = new type[size]; | Combined: Declares and instantiates the array in a single statement. | int[] scores = new int[10]; |
- Annotated Java Examples
When an array is created, Java automatically initializes its elements to a default value based on the data type.
// Example 1: Creating an array of primitive integers
// Creates an array that can hold 5 integer values.
int[] highScores = new int[5];
// At this point, the array `highScores` contains: [0, 0, 0, 0, 0]
// because the default value for the `int` type is 0.
// Example 2: Creating an array of objects (Strings)
// Creates an array that can hold 3 String object references.
String[] studentNames = new String[3];
// At this point, the array `studentNames` contains: [null, null, null]
// because the default value for any object type is `null`.
Accessing and Modifying Elements
To work with an element in an array, you use its index inside square brackets [].
- Syntax Table: Element Access
| Syntax | Purpose | Java Example |
|---|---|---|
arrayName[index] | Access: Retrieves the value of the element at the specified index. | int firstScore = highScores[0]; |
arrayName[index] = value; | Modification: Assigns a new value to the element at the specified index. | highScores[0] = 98; |
- Annotated Java Example
// Create an array to hold four student GPAs.
double[] gpas = new double[4]; // Array is currently [0.0, 0.0, 0.0, 0.0]
// Modify the elements using their indices.
gpas[0] = 3.8; // Set the first element (index 0)
gpas[1] = 2.9; // Set the second element (index 1)
gpas[3] = 4.0; // Set the last element (index 3)
// The array `gpas` now contains: [3.8, 2.9, 0.0, 4.0]
// Note that gpas[2] remains at its default value of 0.0.
// Access an element and print it.
System.out.println("The first student's GPA is: " + gpas[0]); // Prints 3.8
// Access an element and use it in a calculation.
double newGpa = gpas[3] - 0.1; // newGpa becomes 3.9
Tracing & Analysis
Execution Trace
Tracing array modifications is key to understanding how programs work. Let's trace a short sequence of operations.
Code:
int[] data = new int[3];
data[1] = 25;
data[2] = data[1] * 2;
data[0] = data[2] - 10;
Trace Table:
| Line of Code | data[0] | data[1] | data[2] | Array State |
|---|---|---|---|---|
int[] data = new int[3]; | 0 | 0 | 0 | [0, 0, 0] |
data[1] = 25; | 0 | 25 | 0 | [0, 25, 0] |
data[2] = data[1] * 2; | 0 | 25 | 50 | [0, 25, 50] |
data[0] = data[2] - 10; | 40 | 25 | 50 | [40, 25, 50] |
Analysis: The ArrayIndexOutOfBoundsException
Java protects array memory by throwing a runtime error, an ArrayIndexOutOfBoundsException, if you try to use an index that is not valid. Valid indices for an array of length L are 0, 1, ..., L-1.
An index less than
0is invalid.An index greater than or equal to
array.lengthis invalid.
int[] numbers = new int[10]; // Valid indices are 0 through 9.
// This is VALID
numbers[0] = 100; // Accessing the first element.
numbers[9] = 999; // Accessing the last element.
// This will cause an ArrayIndexOutOfBoundsException
// numbers[10] = 50; // ERROR: Index 10 is out of bounds.
// This will also cause an ArrayIndexOutOfBoundsException
// numbers[-1] = 20; // ERROR: Negative indices are not allowed.
Java Syntax Quick-Reference
new type[size]: The operator and syntax used to instantiate a new array object in memory with a specified
sizeandtype.arrayName[index]: The square bracket notation used to access or modify the element at a given
indexwithin an array.arrayName.length: A property (not a method) that holds the total number of elements the array can store. It is an
intvalue.
Core Code Examples & Terminology
Array: A data structure that stores a fixed-size, sequential collection of elements of the same data type.
Element: A single value stored within an array at a specific position.
Index: A zero-based integer that specifies the position of an element within an array. The first element is at index 0.
newkeyword: An operator used to create new objects, including arrays, by allocating memory for them.ArrayIndexOutOfBoundsException: A runtime error that occurs when a program attempts to access an array with an invalid index (one that is less than 0 or greater than or equal to the array's length).Core Snippet 1 (Array Creation):
double[] prices = new double[20];This code creates an array object that can hold 20
doublevalues, with each element initialized to0.0.Core Snippet 2 (Element Modification):
String[] words = new String[5]; words[0] = "Java";This code assigns the
Stringliteral"Java"to the first element (at index 0) of thewordsarray.
Core Skill Check
Code Tracing: What is the final value of
xafter this Java code runs:int[] arr = new int[3]; arr[0] = 5; arr[1] = 10; arr[2] = arr[0] + arr[1]; int x = arr[2];?xwill be15.Debugging: Identify the runtime error in this Java code:
int[] values = new int[100]; values[100] = 5;.ArrayIndexOutOfBoundsException. The largest valid index for an array of size 100 is99.Application: Write a single line of Java code that creates an array named
activeto hold 25booleanvalues.boolean[] active = new boolean[25];
Common Misconceptions & Errors
Off-by-One Errors: A very common mistake is trying to access
array[array.length]. Remember, if an array has a length of 10, its valid indices are 0 through 9.Confusing Size and Maximum Index: The size (
.length) is the total count of elements. The maximum index is alwayslength - 1.Forgetting to Instantiate: Declaring
int[] data;only creates a reference that isnull. You cannot access elements likedata[0]until you instantiate the array withdata = new int[size];.Using Parentheses for
.length:array.lengthis a property, not a method. Writingarray.length()will cause a compile-time error. This is often confused withString.length(), which is a method.
Summary
Arrays are a core tool in Java for organizing and storing fixed-size collections of data of the same type. Creation involves two steps: declaring a reference variable and instantiating the array object using the new keyword and a specified size. Once created, individual elements are accessed and modified using square brackets [] and a zero-based index. The .length property provides the array's size, which is crucial for avoiding the common ArrayIndexOutOfBoundsException that occurs when using an invalid index.