CodeGym /Courses /JAVA 25 SELF /Introduction to Arrays

Introduction to Arrays

JAVA 25 SELF
Level 7, Lesson 1
Available

1. An array is a container of elements

You’ve probably heard that computers can process huge amounts of information. Conditional statements (if-else) and loops (for, while) certainly help with that. But they can only take you so far, because the data being processed needs to be stored somehow.

For this case, Java, like almost all programming languages, has an excellent thing called arrays (Array). They’re also sometimes called tables.

An array is a special object that can store not one value but several.

Arrays (Array) in Java

If earlier we compared a variable to a box (where you can store some value), then an array is more like a box divided into sections. Each section in the “array-box” has its number. Numbering, of course, starts at zero...

Or we can draw another analogy. Let’s compare a single-family house and an apartment building. A single-family house is occupied by one family, while an apartment building is divided into flats. To send a letter to a family living in a single-family house, you specify its unique address. To send a letter to a family living in an apartment, you specify the unique address of the building and the apartment number.

So, an array variable is like a multi-storey building. It can store not one value but several. Such a variable has multypele apartments (cells), each of which can be accessed by its number (index).

To do this, after the variable name, in square brackets, specify the index of the cell you’re addressing. It’s quite simple:


array[index] = value;
Assigning a value to an array cell by index

Where array is the name of the array variable, index is the number of the cell in the array, and value is the value we want to put into the specified cell.

But first let’s figure out how to create arrays.

2. Creating an array of elements in Java

Creating an array of elements in Java

Suppose your program needs to store 100 integers somewhere. Most likely, an array would be suitable. So how do you create it?

If we wanted to store one integer, the int type would be fine, but if we want to store 100 integers, we probably need an array of type int. Here’s what the code to create it would look like:

int[] array = new int[100];
Creating an array of 100 ints

Let’s break down what’s written here.

As you may have already guessed, to the left of the equals sign we have the declaration of a variable named array of type int[]. After the type int come square brackets, which hint that “boxes” of this type can store not one value but several.

To the right of the equals sign we have “object creation” (the word new) with 100 elements (cells) of type int. Not too hard either.

If we wanted to create, say, an array with 20 cells to store floating-point numbers, the creation code would look something like this:

double[] vals = new double[20];
Creating an array of 20 floating-point numbers

The number of cells in an array is called the array size or array length. Because of their ability to store many values, arrays are also called containers.

Important fact: the size of an array container cannot be changed after creation.

You can create a new one, but you cannot change the length of an already created container.

3. Working with array cells

Great, we’ve learned to create arrays, but how do we work with them properly?

Almost the same as with ordinary variables, except that after the array variable name you must specify the number of the cell you’re working with.

Array cell numbering always starts at zero. If we have an array with 10 elements, the numbers (indices) of its cells are 0..9; if the array has 200 elements, then 0..199. And so on by analogy.

Examples:

int[] a = new int[10];	// Create an array of 10 elements of type int.

a[2] = 4;				// Write the value 4 into the cell with index 2.

a[7] = 9;				// Write the value 9 into the cell with index 7.

a[9] = a[2] + a[5];		// Write into the cell with index 9 the sum of the values stored in cells 2 	
                        // (stores 4) and 5 (stores 0). 

Here’s what will be stored in memory after this code is executed:

Working with cells of an int array

The column to the left of the array (in gray) shows the numbers (indices) of the cells. The inserted values are stored in the cells: 4, 9, and 4. Immediately after creation, array cells are filled with zeros.

Important. All cells of an array have the same data type. If we created an array of strings String, only strings can be stored in its cells. The array’s data type is set when it’s created. Neither the data type nor the length of the array can be changed later.

4. Arrays in memory

The pictures in the previous examples are a bit imprecise.

When creating arrays (as with creating strings), two memory blocks are allocated: one for storing the array itself (the container), and the second for the variable that stores its address. The clarified situation is shown in the image below:

Arrays in memory

In green is an array with 10 elements of type int and a variable of type int[] that holds the address (reference) of the int array in memory.

For comparison, in blue is an ordinary variable of type int that holds the value 199.

Doesn’t it resemble how strings are stored in memory?

Exactly—strings. And just like when working with strings, “variables of array type” can be assigned to each other:

int[] a = new int[10];		// Create an array of 10 elements of type int.

a[2] = 4;					// Write the value 4 into the cell with index 2.
a[7] = 9;					// Write the value 9 into the cell with index 7.

int[] b = a;				// Store in variable b the address contained in variable a.
                            // Now a and b point to the same array object in memory.

a[9] = b[2] + a[7];			// Write into the cell with index 9 of the array object the sum of the values
                            // stored in cells 2 (stores 4) and 7 (stores 9). 

In this case, the array object will remain where it was, and the variables a and b will store identical addresses (references) to the same object. See the picture:

Arrays in memory 2

5. Working with arrays in more detail

You can create an array of absolutely any type. To do this, you just need to write square brackets after the type name. The general form of array creation looks like this:

type[] name = new type[count];
Canonical form of creating an array

Where type is the type of the array elements (cells) that we will store in the array. Name is the name of the variable by which we will access the array, and count is the number of cells in the array.

The example above shows the canonical form: creating an array variable and creating an array object. In fact, these are two independent constructs. You can create the array variable and the array object separately:

type[] name;
name = new type[count];
Create the variable and the array separately

One more important point

Variables and even entire expressions can act as the array index and as the number of array elements.

Examples:

int n = 100;
int[] a = new int[n];			// 	Create an array of n elements

int n = 100;
int[] a = new int[n * 2 + 3];	// 	Create an array of 203 elements

int n = 100;
int[] a = new int[n];
a[n-1] = 2;					// a[99] = 2;
a[n-2] = 3;					// a[98] = 3;
a[n/5] = a[n-1] + a[n-2]	// a[20] = a[99] + a[98];

Out-of-bounds access

By the way, note that if you try to access an array cell by an index that the array doesn’t have (in our case, all integers except 0..99), the program will crash with an error ArrayIndexOutOfBoundsException — index outside the bounds of the array.

6. Array length

As we saw in the previous example, you can create an array-type variable separately and then somewhere in the code assign it a value (a reference to an array object). You can even do this:

int[] array;			//	Create an array variable of type int[]
if (a < 10)				// If variable a is less than 10,
   array = new int[10];	// then create an array of 10 elements.
else					// Otherwise
   array = new int[20];	// create an array of 20 elements 

And how do you work with such an array further? How do you find out how many elements it has?

For this, an array has a special property (variable) — length. You can get the length of an array using the following expression:

array.length;
Getting the array length via the length property

Where array is the name of the array variable, and length is the name of a property of the array object. The value of length cannot be changed: you can assign the length value to other variables, but you cannot assign anything to it (the program simply won’t compile).

Here’s how we can continue the previous example:

int[] array;			//	Create an array variable of type int[]
if (a < 10)				// If variable a is less than 10,
   array = new int[10];	// then create an array of 10 elements.
else					// Otherwise
   array = new int[20];	// create an array of 20 elements 

for (int i = 0; i < array.length; i++)	// Loop over all array elements: from 0 up to array.length — 1
{
   System.out.println(array[i]);
}

7. Facts about arrays in Java

Let’s summarize the known facts about arrays:

  • Fact 1. An array consists of many cells.
  • Fact 2. Access to a specific cell is through specifying its number.
  • Fact 3. All cells are of the same type.
  • Fact 4. The initial value for all cells is 0 and null (if the cell stores an address), false (for type boolean).
  • Fact 5. String[] list is just a variable declaration: the container itself (the array object) has not yet been created. To work with it, you need to create an array (container) and put it into this variable, and only then use it. See the example below.
  • Fact 6. When we create an array object (container), we need to specify its length — how many cells it has. This is done with a command of the form: new TypeName[n];
  • Fact 7. You can find the length of an array via the .length property.
  • Fact 8. After an array is created, you cannot change either the type of its elements or their number.
String s;				// s equals null
String[] list;			// list equals null

list = new String[10];	// The variable list holds a reference to an object — an array of strings with 10 elements.
int n = list.length;	// n equals 10

list = new String[0];	// Now list contains an array of 0 elements. 
                        // The array exists, but it cannot store elements.

list = null;
System.out.println(list[1]); // An error will be generated — the program will crash. 
                            // list contains a null reference — null

list = new String[10];
System.out.println(list[10]);	// An error will be generated — out-of-bounds access.
//	If list contains 10 elements/cells, then the allowed indices are: 0 1 2 3 4 5 6 7 8 9 — 10 in total. 	
1
Task
JAVA 25 SELF, level 7, lesson 1
Locked
Preparing the Adventurer's Backpack 🎒
Preparing the Adventurer's Backpack 🎒
1
Task
JAVA 25 SELF, level 7, lesson 1
Locked
Assessing a List of Favorite Programming Languages 💬
Assessing a List of Favorite Programming Languages 💬
1
Task
JAVA 25 SELF, level 7, lesson 1
Locked
Configuring the weather station sensors ☀️
Configuring the weather station sensors ☀️
1
Task
JAVA 25 SELF, level 7, lesson 1
Locked
Filling the tournament scoreboard 🏆
Filling the tournament scoreboard 🏆
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 1, San Diego, United States
8 November 2025
'tables'