Course contentsShow
← Java
Lesson 236 of 2,8706. ArraysFree lesson

Creating Arrays with new

Use the new keyword to instantiate arrays, specifying the size: new int[10].

Creating Arrays with new

You'll learn how to actually allocate memory for an array using the new keyword.

Why We Need new

In the previous lesson, you learned that declaring an array like int[] numbers; only creates a reference variable—it doesn't actually create the array itself. Think of it like reserving a parking spot name ("Spot A") without actually painting the lines or paving the ground. To create the actual array in memory, you use the new keyword.

Using new to Instantiate Arrays

The new keyword allocates memory for a fixed number of elements. Here's the syntax:

int[] numbers = new int[10];

This creates an array that can hold exactly 10 integers. The number in brackets is the size of the array—how many elements it contains. Once created, this size cannot change.

Breaking Down the Syntax

  • int[] – The type of the reference variable (array of integers)
  • numbers – The variable name
  • = – Assignment operator
  • new – Keyword that allocates memory
  • int[10] – Creates an array with 10 integer slots

You can also split declaration and instantiation:

double[] prices;          // Declaration only
prices = new double[5];   // Instantiation with size 5

Default Values

When you create an array with new, Java automatically initializes all elements to default values: 0 for numeric types, false for boolean, and null for reference types.

Key Takeaway: Use the new keyword followed by the array type and size in brackets to allocate memory for an array—like new int[10] creates space for 10 integers.