More Array Basics

In this lesson, we will continue our introduction to using arrays in a Java program.

Declaring and initializing an array

Although the elements of an array are initially given default entries when the array is created, we can initialize the elements explicitly when we declare the array. To do so, we write the data type of its elements, a pair of square brackets, the assignment operator, and a list of values separated by commas and enclosed in curly brackets. For example, to define an array of three integers, we write:

int[] data = {10, 20, 30};

Now data[0] is 10, data[1] is 20, and data[2] is 30. Also, note that data.length is 3. That is, the length of the array is the minimum number of elements required for the values listed between the curly brackets. In other words, the previous Java statement is equivalent to the following sequence of statements:

int[] data = new int [3];
data[0] = 10;
data[1] = 20;
data[2] = 30;

📝 Syntax: Initializing an array when it is declared

entry-type[] array-name = {v1, v2, . . . , vn};

where entry-type is any primitive type or class type, and the entries vi are values of type entry-type. The portion on the left side of the assignment operator is the array declaration; the portion on the right side creates the array.

Example:

String[] notes = {"do", "re", "mi", "fa", "so", "la", "ti", "do"};

Here, notes.length is 8.

Get hands-on with 1200+ tech skills courses.