Concepts / Introduction to Arrays

Introduction to Arrays

An array type is the base type followed by a pair of empty square brackets, such as int[] or String[].

  • Programming

Why a Single Row of Boxes Is Not Always Enough

Most arrays you have met so far can be pictured as one line of boxes. Each box holds one value and is identified by its position in the line. That picture works well for a list of test scores or a sequence of temperatures. Many real problems, however, have information that naturally fits into a grid. A seating chart, a calendar month, a spreadsheet, or a game board all organize their data in rows and columns. A two-dimensional array is the data structure designed for that kind of layout.

Before any of that, this article starts with the basic mechanics of a one-dimensional array, because the same two-step idea applies to every array, including grids. Keep one question in mind as you read: if you were given only a row number and a column number, could you find the one element they point to?

What do you think happens?

Suppose a program runs the single line int[] a; and nothing else. Does the variable a now refer to an array?

  • Yes, the line creates an array of ints

  • No, the line only gives the variable a type so it can refer to an array later

Reveal answer
Answer:

No, the line only gives the variable a type so it can refer to an array later.

Declaring a variable gives it a type, which tells the compiler what kind of thing the variable may refer to. The source states directly that declaring a variable does not make the actual array. The array has to be created separately with the new operator.

Reading the Type of an Array

An array type is built from two parts: the base type of the array, followed by a pair of empty square brackets. The base type is the type of each element the array will hold. The brackets mark the type as an array type rather than a single value of the base type. So an array of ints has the type int[], and an array of Strings has the type String[].

Declaring an Array Variable

Once you have the type, a variable is declared by writing the type, a space, and the variable name, followed by a semicolon. For example, a variable named names that is meant to refer to an array of Strings is declared with the type String[] followed by the name. The declaration tells the compiler what the variable may refer to. The name is what you will later use to reach the array.

java
Notes on the code
  • int[] is the type: the base type int followed by empty square brackets
  • a is the variable name, which will later be used to reach the array
  • The semicolon ends the statement. No array has been created yet.

Tracing the Variable Before and After Creation

The diagram below compares the state of the variable a before and after the creation step. Before creation, the variable has a type but refers to nothing. After creation, the variable refers to one array object that holds five elements. The source gives only this logical structure: one variable, one array, and an indexed set of elements. It does not describe how the elements are stored in memory, so the figure does not show that either.

atype int[]atype int[]no array yetint arrayfive elementsrefers to
After the declaration int[] a; and then the creation step run, what does the variable a refer to, and how is that different from the array object that new creates?

Creating the Array with new

Creating an array is the step that produces the actual array. In Java this is done with an operator named new. The source notes that arrays in Java are objects and that this special syntax is related to that fact, but the details of object creation are not needed at this stage. What matters is the pattern you write.

java
Notes on the code
  • A is the array variable on the left, so it receives the new array as its value
  • new is the operator that creates the array
  • int is the base type: the type of each element
  • [5] is the length: creating an array means deciding how many elements it has
Worked example

Reading an array creation statement from left to right

Read the statement names = new String[3]; and say what each part contributes.

  1. 1
    Identify the variable

    names is on the left of the assignment, so it receives the new array as its value.

  2. 2
    Identify the operator

    new is the operator that produces the actual array.

  3. 3
    Identify the base type

    String is the base type, the type of each element the array will hold.

  4. 4
    Identify the length

    [3] gives the length. The length is required, because it decides how many elements the array has.

Result

The variable names now refers to a new array of three String elements. This example was written for this article to match the source's pattern, not taken from the source.

Running Declaration and Creation in Order

The two steps often appear on neighboring lines and mention the same variable name, which makes them easy to confuse. Read them in order. The declaration gives the variable a type. The creation statement supplies the array the variable will refer to. The source states that an array must be created before it is used, so creation must come before any work on the elements.

Code walkthrough
int[] a;
a = new int[5];
  1. 1
    Line 1 the declaration sets the type of a so that a may refer to an array of ints.
  2. 2
    Line 2 new int[5] produces the array object, and the assignment makes a refer to it.
  3. 3
    After line 2, a refers to an array with five elements, indexed from 0 to 4.
  • Line 1 declares a with the type int[]. No array exists yet.
  • Line 2 creates an array of five ints and assigns it to a.
java
Notes on the code
  • The same two-step method works for a different base type and length.
  • Declaration first, then creation, then the array can be used.
EASY

Write the declaration and creation statements for an array of double values with a length of 4, using the variable name prices. Check that the declaration comes first and the creation statement follows it.

Hints
  • The base type is double, so the declared type is double[].
  • The creation statement uses new, the base type double, and the length 4 in square brackets.

Mistakes Beginners Make With Array Variables

  • Common mistake

    Assuming the declaration creates the array

    What it looks like
    int[] a; followed by a line that reads a[0] with no creation statement
    Why it fails

    The declaration only gives a a type. The source states that declaring a variable does not make the actual array.

    Do this instead

    Add a creation statement such as a = new int[5]; before any code that works with the elements.

  • Common mistake

    Using the variable before creation

    What it looks like

    Reading or writing elements of names before names = new String[3]; has run

    Why it fails

    The variable has no array yet, so there is nothing for it to refer to. The source says arrays must be created before use.

    Do this instead

    When you read a declaration, check the following lines for the creation statement, and confirm it runs first.

  • Common mistake

    Leaving out the length in the creation statement

    What it looks like

    new int; instead of new int[5];

    Why it fails

    Creating an array means deciding how many elements it has, and the source says the length is required.

    Do this instead

    Write the base type followed by the length in square brackets.

Two-Dimensional Arrays as Grids

A two-dimensional array organizes its elements in a rectangular grid made of rows and columns. Each row runs across the grid and holds one element for every column, and each column runs down the grid and holds one element for every row. This layout suits data such as tables and boards, where a position is naturally described by two coordinates rather than one.

A grid is described by its number of rows and its number of columns, usually stated rows first, then columns. A grid with five rows and seven columns is called a 5-by-7 grid. The source does not show the code for creating a two-dimensional array, so this article focuses on how the grid is organized and numbered rather than on that syntax.

Counting the Cells in a Grid

The total number of elements in a rectangular grid is found by multiplying the number of rows by the number of columns. Each row contributes one element for every column, so the rows together give the total. A 5-by-7 grid holds 35 elements, which is the example the source uses.

Rule

Worked example

Counting cells in a 3-by-4 grid

How many cells does a grid with 3 rows and 4 columns contain, and how does each row contribute?

  1. 1
    Read the counts

    The grid has 3 rows and 4 columns.

  2. 2
    Multiply

    Total cells = 3 x 4 = 12.

  3. 3
    Check by rows

    Each of the 3 rows holds 4 cells, and 3 rows of 4 cells gives 12 cells in total.

Result

The grid holds 12 elements. This example was written for this article, following the source's counting rule.

Locating a Cell by Row and Column

Rows and columns are both numbered starting from 0, so the last index is always one less than the count. An element is identified by its row number followed by its column number, and the pair picks out exactly one cell. The row number always comes first. You can read the pair as a path that moves down the grid to the row and then across to the column.

row 0, col 0row 1, col 0row 2, col 0row 0, col 1row 1, col 1row 2, col 1target elementrow 0, col 2row 1, col 2row 2, col 2row 0, col 3row 1, col 3row 2, col 3
In a 2D array, which cell does row 2, column 1 point to when counting starts at 0 for both rows and columns?
Worked example

Finding the cell at row 2, column 1

In a 3-by-4 grid with rows and columns numbered from 0, which cell does the pair row 2, column 1 identify?

  1. 1
    Read the row number first

    The row number is 2, so move to the third row. Rows are numbered 0, 1, 2, so this is the last row.

  2. 2
    Read the column number second

    The column number is 1, so move across to the second column. Columns are numbered 0, 1, 2, 3.

  3. 3
    Combine the two

    The pair picks out exactly one cell: the bottom row, second column.

Result

The pair row 2, column 1 identifies the element in the bottom row, second column. This example was written for this article, applying the source's row-then-column rule.

The same procedure works for any cell, and only the two numbers change. The element at row 0, column 0 is always the top-left cell of the grid. The element at the last row and last column is always the bottom-right cell.

Common Mistakes With Grid Positions

  • Common mistake

    Counting rows and columns from 1

    What it looks like

    Treating row 3, column 1 in a 3-by-4 grid as the bottom row

    Why it fails

    Rows and columns are both numbered starting from 0, so a 3-row grid has rows 0, 1, and 2.

    Do this instead

    Subtract one from the human count, or use the index range 0 to count minus 1 for each axis.

  • Common mistake

    Reading the column number first

    What it looks like

    Reading the pair row 2, column 1 as column 2, row 1

    Why it fails

    An element is identified by its row number followed by its column number, so the order matters.

    Do this instead

    Always read the row first, then the column.

  • Common mistake

    Assuming the drawing shows memory

    What it looks like

    Expecting the grid picture to show where each element sits in memory

    Why it fails

    The source says the grid shows the logical structure only, and it does not describe the storage mapping.

    Do this instead

    Reason with rows and columns when writing code, and let the language handle storage.

Checking Your Grid Reasoning

MEDIUM

A grid has 4 rows and 6 columns. First, how many elements does it hold? Then, which cell does the pair row 3, column 5 identify, and why is it the bottom-right cell?

Hints
  • Multiply the number of rows by the number of columns.
  • Rows and columns are numbered from 0, so the last row is 3 and the last column is 5.

Recap of Declaring, Creating, and Locating

An array variable is declared with an array type, such as int[] or String[], and the declaration only gives the variable a type. The array itself is produced by new, which needs a base type and a length. Once the array exists, a two-dimensional array organizes its elements into rows and columns, and a row and column pair identifies one cell.

Key Takeaways

  • An array type is the base type followed by a pair of empty square brackets, such as int[] or String[].
  • Declaring an array variable gives it a type so it can refer to an array, but the declaration does not create the array.
  • The new operator, given a base type and a length, creates the array, and the array must exist before its elements are used.
  • A two-dimensional array is a rectangular grid of rows and columns, with n rows and m columns holding n x m elements.
  • Rows and columns are both numbered from 0, and a row number followed by a column number identifies exactly one element.