Java • Collections and Strings

Declaring & Initializing Arrays — Declare, allocate, and initialize arrays

Learn to store and manage collections of related data using Java arrays from the ground up.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Imagine you are building a program that tracks the test scores for every student in your class. Without arrays, you would need to create a separate variable for each student — score1, score2, score3, and so on. That approach becomes impossibly tedious when the class has thirty students, let alone thousands of data points. The array was invented precisely to solve this problem: it lets you store many values of the same type under a single variable name and access each one by its position.

1950s • Early Machine-Level Arrays

Assembly language programmers used contiguous blocks of memory addresses to store related data. This raw technique became the conceptual ancestor of the modern array.

1972 • C Language & Static Arrays

The C programming language introduced a clean syntax for declaring arrays that mapped directly to memory. Java later inherited much of its array notation from C.

1995 • Java 1.0 Released

Java launched with built-in array support. Unlike C, Java arrays are objects that know their own length, check bounds at runtime, and prevent buffer overflows — making them safer for beginners.

1998 • Java Collections Framework

Java 2 introduced ArrayList and other dynamic collections that build on top of arrays, offering resizable storage. Understanding raw arrays remains essential because collections use them internally.

So the core question this lesson answers is: How do you declare, allocate memory for, and fill a Java array with values? Mastering these three steps gives you the foundation for every collection-based structure you will encounter later.

SECTION 2

Core Principles & Definitions

Before writing any code, you need to understand the three distinct steps involved in creating an array. Each step plays a specific role, and Java lets you combine them in different ways depending on the situation. Let's break them down.

1

Declaration

You tell the compiler the data type of the elements and the name of the array variable. No memory is allocated yet. Example: int[] scores;
2

Allocation (Instantiation)

You use the new keyword to reserve a fixed block of memory for a specific number of elements. Example: scores = new int[5];
3

Initialization

You assign actual values to each position (index) of the array. You can do this element-by-element or all at once with an initializer list. Example: scores[0] = 95;
4

Zero-Based Indexing

The first element of every Java array lives at index 0, not index 1. An array with 5 elements has valid indices 0 through 4. Accessing index 5 throws an ArrayIndexOutOfBoundsException.
5

Fixed Size

Once you allocate an array, its length cannot change. If you need more room, you must create a new, larger array and copy the elements over. The property .length tells you the size.
✦

KEY TAKEAWAY

Think of an array like a row of lockers in a school hallway. Declaring the array is like deciding you need lockers for storing books. Allocating is like having the school install exactly 10 lockers in a row. Initializing is like actually placing a book inside each locker. The lockers are numbered starting from 0, and once they're installed, you can't magically add more lockers to that same row.

SECTION 3

Visual Explanation — Array in Memory

The diagram below shows what happens in memory when you write int[] scores = {95, 88, 76, 100, 64};. The variable scores is a reference that points to a contiguous block of five integer slots on the heap. Each slot is accessed by its index.

Array Memory Layout: int[] scores = {95, 88, 76, 100, 64};Stack (variable)scoresreferenceHeap (array object, length = 5)95887610064[0][1][2][3][4]Three Syntax Approaches1. Separate Stepsint[] a;a = new int[5];a[0] = 95;a[1] = 88;// ... etc.2. Declare + Allocateint[] a = new int[5];Elements default to 0.Assign values laterusing index notation.3. All-in-Oneint[] a = {95, 88, 76, 100, 64};Size is inferredfrom the values.
The top half shows how the reference variable scores on the stack points to the array object on the heap. The bottom half compares three common syntax patterns for creating arrays.

Notice that every element sits next to its neighbor in memory. This contiguous layout is what makes arrays so fast — the computer can jump to any index in constant time because it simply calculates an offset from the starting address. The trade-off is that you must decide the size up front.

SECTION 4

How It Works — Syntax Deep Dive

Java provides three main syntax patterns for creating arrays. Each pattern combines the declaration, allocation, and initialization steps in a slightly different way. Understanding when to use each one will make your code cleaner and more efficient.

Pattern 1 — Declare, Then Allocate, Then Initialize

SEPARATE STEPS SYNTAX

type[]name;→name=newtype[size];→name[index]=value;type[] name; → name = new type[size]; → name[index] = value;

type = the data type (int, double, String, etc.). size = number of elements. index = position (starting at 0).

This pattern is useful when you know you need an array but don't yet know the values. After allocation, every element is automatically set to a default value: 0 for numeric types, false for booleans, and null for object references.

Pattern 2 — Declare and Allocate in One Line

COMBINED DECLARATION + ALLOCATION

type[]name=newtype[size];type[] name = new type[size];

This is the most common pattern when you plan to fill values later, perhaps inside a loop. The array is created with default values.

Pattern 3 — Initializer List (All-in-One)

INITIALIZER LIST SYNTAX

type[]name=value0,value1,value2,…;type[] name = {value₀, value₁, value₂, …};

Java counts the values in the curly braces and allocates the array automatically. You do not use the new keyword here. This is ideal when you know all values at compile time.

⚠

Common Pitfall

You cannot use an initializer list after the declaration line. The code int[] a; a = {1, 2, 3}; will not compile. If you need to assign an initializer list later, use a = new int[]{1, 2, 3}; — note the explicit new int[] before the braces.

SECTION 5

Default Values & Data Types

When you allocate an array with new but don't explicitly set values, Java fills every slot with a default value that depends on the element type. This is different from local variables, which must be initialized before use. Knowing the defaults helps you avoid subtle bugs.

Element TypeExample DeclarationDefault Value
intint[] nums = new int[3];0
doubledouble[] gpa = new double[4];0.0
booleanboolean[] flags = new boolean[2];false
charchar[] letters = new char[5];'\u0000' (null character)
String (or any object)String[] names = new String[3];null

Default values by element type when using the new keyword

Lifecycle of an Array — From Declaration to UseDECLAREint[] scores;ALLOCATEscores = new int[5];INITIALIZEscores[0]=95; scores[1]=88;…State of scores[] at Each StageAfter Declarationnull (no object)After Allocation00000After Initialization95887610064[0][1][2][3][4]💡 Rememberscores.length == 5 | Valid indices: 0, 1, 2, 3, 4 | scores[5] → ArrayIndexOutOfBoundsException
This diagram traces the lifecycle of the scores array through all three stages. Notice how after allocation but before initialization, every slot holds the default value 0.

One detail worth memorizing: the .length property of an array is not a method — there are no parentheses after it. This is different from String's .length() method. Writing scores.length() on an array will cause a compile error.

SECTION 6

Worked Example — Building a Student Grade Tracker

Let's walk through a complete example where we declare, allocate, and initialize an array of student grades, then compute the class average. This mirrors a real scenario you might encounter in a programming assignment.

Compute the Average of Five Test Scores

  1. 1

    Step 1 — Declare and Initialize with an Initializer List

    We know all five scores ahead of time, so we use the all-in-one syntax. Write: int[] grades = {92, 85, 78, 96, 88};. Java creates an array of length 5 and fills in each value.
    Array created: grades = [92, 85, 78, 96, 88]
  2. 2

    Step 2 — Verify the Length

    Check the array's size using grades.length. Since we provided five values, this evaluates to 5. We will use this in our loop boundary.
    grades.length → 5
  3. 3

    Step 3 — Sum the Elements Using a for Loop

    Declare a variable int sum = 0; and loop from index 0 to grades.length - 1: for (int i = 0; i < grades.length; i++) { sum += grades[i]; }. After the loop, sum = 92 + 85 + 78 + 96 + 88.
    sum → 439
  4. 4

    Step 4 — Compute the Average

    Divide the sum by the number of elements. Use double average = (double) sum / grades.length;. The cast to double ensures we get a decimal result rather than integer division.
    Average = 439 ÷ 5 = 87.8
  5. 5

    Step 5 — Print the Result

    Use System.out.println("Class average: " + average); to display the output. The full program is only about 8 lines, demonstrating how arrays simplify working with multiple related values.
    Output: Class average: 87.8

SECTION 7

Arrays vs. Other Storage Options

Arrays are powerful, but they aren't the only way to store collections of data in Java. The table below compares arrays with two alternatives you'll encounter soon: separate variables and ArrayList. Understanding these trade-offs helps you choose the right tool for each task.

FeatureSeparate VariablesArrayArrayList
Number of itemsFixed at compile timeFixed once allocatedGrows and shrinks dynamically
Access by indexNot possibleYes — arr[i]Yes — list.get(i)
LoopingTedious — each variable named individuallyEasy with for loopEasy with for-each loop
Primitive types?YesYesNo — requires wrapper classes (Integer, etc.)
PerformanceN/AFastest — direct memory accessSlightly slower due to object overhead

Comparing arrays to other storage options

✦

KEY TAKEAWAY

Use an array when you know how many elements you need and performance matters (for example, storing pixel data in an image). Use an ArrayList when the number of elements might change at runtime (for example, a shopping cart where users add and remove items). Think of an array as a fixed-size parking lot and an ArrayList as a valet service that can always find room for one more car.

SECTION 8

Connection to Advanced Topics

Once you are comfortable with one-dimensional arrays, you'll encounter more advanced structures that build directly on the same declare-allocate-initialize pattern. Two of the most important are multidimensional arrays and enhanced for loops. The table below previews how today's concepts extend.

ConceptWhat You Learned TodayWhere It Leads
Declarationint[] arr;int[][] grid; — a 2D array (array of arrays)
Allocationnew int[5]new int[3][4] — 3 rows, 4 columns
Traversalfor (int i = 0; ...)for (int val : arr) — enhanced for-each loop
Utility MethodsManual loopsArrays.sort(), Arrays.toString() from java.util.Arrays
Dynamic sizingNot supportedArrayList<Integer> — resizable collection backed by arrays

From basic arrays to advanced structures

Every one of these advanced topics relies on the same mental model: an array is a fixed-size, indexed container that lives on the heap. If you understand that, 2D arrays are just arrays whose elements are themselves arrays, and ArrayList is just a class that creates larger arrays behind the scenes when it runs out of room.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain the difference between declaring an array and allocating an array. What happens if you try to access an element of an array that has been declared but not yet allocated?
Show answer
Declaring an array (e.g., int[] nums;) creates a reference variable that can point to an array object, but no array object exists yet — the reference is null. Allocating (e.g., nums = new int[3];) actually creates the array object in heap memory with space for 3 integers. If you try to access an element before allocation, such as nums[0], Java will throw a NullPointerException at runtime because the reference doesn't point to any object.

Question 2: BASIC CALCULATION

What is the output of the following code? double[] temps = new double[4]; temps[0] = 72.5; temps[2] = 68.0; System.out.println(temps[1] + " " + temps[3]);
Show answer
The output is 0.0 0.0. When you allocate a double array with new double[4], all four elements default to 0.0. The code only assigns values to indices 0 and 2, so indices 1 and 3 retain their default value of 0.0. This is a key feature of Java arrays — they always have well-defined default values after allocation.

Question 3: INTERMEDIATE

Write a complete Java statement that creates a String array named colors containing "red", "green", and "blue" using an initializer list. Then write a for loop that prints each color on its own line.
Show answer
Declaration with initializer list: String[] colors = {"red", "green", "blue"};. The loop: for (int i = 0; i < colors.length; i++) { System.out.println(colors[i]); }. Notice we use i < colors.length (strictly less than) because the last valid index is colors.length - 1, which is 2. Using <= would cause an ArrayIndexOutOfBoundsException on the final iteration.

Question 4: APPLIED

A teacher stores daily high temperatures for a week in int[] highs = {85, 90, 78, 92, 88, 76, 83};. Write code that finds and prints the maximum temperature. What value does your code produce?
Show answer
Start with int max = highs[0]; and loop through the remaining elements: for (int i = 1; i < highs.length; i++) { if (highs[i] > max) { max = highs[i]; } }. After the loop, max is 92 (found at index 3). We initialize max to the first element rather than 0 because all temperatures could theoretically be negative, and starting at 0 would give a wrong result in that case.

Question 5: CRITICAL THINKING

A student writes int[] a = new int[5]; int[] b = a; b[0] = 99; and is surprised that a[0] is now 99 as well. Explain why this happens, and describe how you would create a truly independent copy of array a.
Show answer
In Java, arrays are objects, and the variable name is a reference (like a pointer) to the object on the heap. When you write int[] b = a;, you are copying the reference, not the array itself. Both a and b point to the same block of memory, so changes through one name are visible through the other. To create an independent copy, you can allocate a new array and loop through: int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) { b[i] = a[i]; }. Alternatively, use int[] b = Arrays.copyOf(a, a.length); from java.util.Arrays.

SUMMARY

Lesson Summary

Summary

A Java array is a fixed-size, indexed collection that stores elements of the same type in contiguous memory. Creating an array involves three steps: declaration (specifying the type and name, e.g., int[] scores;), allocation (reserving memory with new, e.g., new int[5]), and initialization (assigning actual values either element-by-element or with an initializer list like {95, 88, 76}). These three steps can be combined on a single line.

Arrays use zero-based indexing, so valid indices range from 0 to length − 1. Uninitialized elements receive default values (0 for numbers, false for booleans, null for objects). The .length property (no parentheses) gives the array's size. Because arrays are objects, assigning one array variable to another copies the reference, not the data. Mastering these fundamentals prepares you for multidimensional arrays, ArrayList, and the entire Java Collections Framework.

Varsity Tutors • Java • Declaring & Initializing Arrays