01 / 20
5 3 8 1 9

Declaring & Initializing
Arrays in Java

Master the fundamentals of declaring, allocating, and initializing arrays: the backbone of organized data in Java.

AP Computer Science A Java

What Is an Array?

An array is a fixed-size, ordered collection of elements that share the same data type. Think of it as a row of numbered boxes, each holding one value. You access each box by its index: an integer starting at 0.

42 17 83 5 61 [0] [1] [2] [3] [4] length = 5

Why Use Arrays?

Without arrays, storing 100 test scores requires 100 separate variables. Arrays let you hold all values in a single named structure and access any element instantly by index.

Organized
Group related data under one variable name instead of dozens of separate variables.
Efficient
Loop through all elements using a single for loop rather than repetitive code.
Fast Access
Jump directly to any element via its index: constant-time access for every position.

Key Vocabulary

Element
A single value stored inside the array at a particular position.
Index
The integer position of an element. Always starts at 0 in Java.
Length
The total number of elements. Access via arr.length (no parentheses).

The Three Steps to Create an Array

1
Declare: Tell the compiler the variable name and element type using square brackets: int[] scores;
2
Allocate: Reserve space in memory with new and specify the size: scores = new int[5];
3
Initialize: Assign values to each slot: scores[0] = 95; or use a shortcut literal.

Declaration & Allocation Syntax

int [] scores = new int [ 5 ] ; Data Type Array Marker Name Allocate Size

Default Values After Allocation

When you allocate an array with new, Java automatically fills every slot with a default value based on the element type:

Element Type Default Value
int, short, byte, long0
double, float0.0
booleanfalse
char'\u0000'
Object references (String, etc.)null

Two Ways to Initialize

Using new + assignment
Declare with new, then assign each element individually. Best when values are computed at runtime.
Array Initializer Literal
Provide values inside curly braces at declaration. Best when you know the values in advance.
// Approach 1: new + element-by-element
int[] ages = new int[3];
ages[0] = 15;  ages[1] = 17;  ages[2] = 16;

// Approach 2: Initializer literal
int[] agesToo = {15, 17, 16};

How Arrays Live in Memory

STACK scores 0x3A7F HEAP 95 88 76 [0] [1] [2] length = 3 (read-only field) Variable holds a reference (address) Actual data lives on the heap

How to Apply It: Step-by-Step

1
Choose the element type: What kind of data will you store? (int, double, String, etc.)
2
Decide on a size: How many elements do you need? This is permanent once allocated.
3
Declare and allocate: Write type[] name = new type[size]; or use the initializer literal type[] name = {values};
4
Populate values: Assign elements by index, or rely on the literal. Verify with name.length.
5
Access elements: Use name[index] to read or write. Always stay within 0 to \( \text{length} - 1 \).

Example 1: Storing Test Scores

// Declare + allocate an array of 4 scores
int[] scores = new int[4];

// Initialize each element
scores[0] = 92;
scores[1] = 85;
scores[2] = 78;
scores[3] = 96;

System.out.println(scores[2]); // Output: 78
System.out.println(scores.length); // Output: 4
92 85 78 96 [0] [1] [2] [3] accessed

Example 2: String Array Literal

// Initializer literal: size is inferred as 4
String[] days = {"Mon", "Tue", "Wed", "Thu"};

System.out.println(days[0]);      // "Mon"
System.out.println(days.length);  // 4

// Overwrite an element
days[3] = "Fri";
System.out.println(days[3]);  // "Fri"

Example 3: Looping Through an Array

double[] temps = {72.5, 68.3, 74.1, 69.8, 71.0};

double sum = 0;
for (int i = 0; i < temps.length; i++) {
    sum += temps[i];
}
double avg = sum / temps.length;
System.out.println(avg); // 71.14

Common Mistakes

✕ Off-by-One Error
Using \( \le \) instead of \( < \) in a loop condition causes an ArrayIndexOutOfBoundsException at the last iteration.
✕ Uninitialized Array
Writing int[] arr; only declares a reference. If you try to use it before initializing (e.g., arr[0] = 5;), you'll get a compile-time error.
✕ Size in Literal
Writing int[3] arr = {1,2,3}; is illegal syntax. With an initializer literal, do not put a number in the brackets.

Summary Comparison

Feature new + Assignment Initializer Literal
Syntax int[] a = new int[n]; int[] a = {1, 2, 3};
Size specified? Explicitly Implicitly (counted)
Initial values Defaults (0, null, etc.) Your supplied values
Best for Dynamic / computed data Known constants
Can reassign later? Elements: yes. Size: no Elements: yes. Size: no

Question 1 of 5

Which declaration correctly creates an array of 10 doubles in Java?

Question 2 of 5

After the line int[] arr = new int[5]; executes, what is the value of arr[3]?

Question 3 of 5

Given: String[] colors = {"red", "green", "blue"};
What does colors.length return?

Question 4 of 5

Which code will cause an ArrayIndexOutOfBoundsException at runtime?

Question 5 of 5

What is the output of the following code?

int[] nums = {4, 8, 15, 16};
nums[1] = nums[3] + 2;
System.out.println(nums[1]);