Skip to content

Introduction To Array Data Structure

This article is an introductory lesson on array data structure with sketches, memory diagrams, strengths, and weaknesses with examples.

Gopi Gorantala
Gopi Gorantala
4 min read
Introduction To Array Data Structure

Table of Contents

Introduction

Arrays are built in most programming languages. They are the most fundamental data structures of all in computer science. Arrays are the building blocks for many other, more complex data structures.

Why do we need an array to store elements? Why can't we make use of int primitive type?

Why not make use of primitives?

In Java int takes 4 bytes. So the declaration below occupies 4 bytes of memory.

int a = 100;

What if we want to store six int values (or 24 bytes)? We need to use six different variables individually, each occupying 4 bytes so that the total will be 6 * 4 = 24 bytes.

// each of the following occupies 4 bytes, which is 6 * 4 bytes
int a1 = 100;
int a2 = 200;
int a3 = 300;
int a4 = 400;
int a5 = 500;
int a6 = 600;

Creating six different variables is a bit dirty and not a good idea. What if we wanted to store a million entries, are we supposed to create a million different variables? 😢 Isn't this bad coding?

Instead, we store the million items in an array sequentially in an int[] array. This can be achieved easily by following the declaration and initialization with values.

int[] array = {100, 200, 300, 400, 500, 600};

Isn't the array beautiful? 🤩

What is an array?

In Java and many other languages, arrays are static(fixed size). Array organizes items sequentially, one after another, in memory.

The items could be Integer, String, Object, – anything. The items are stored in contiguous (adjacent to each other) memory locations.

Each position in the array has an index, starting at the 0th index. In Java, integers take 4 bytes, so the memory addresses of each adjacent element are added by 4 bytes.

Sketch

A simple sketch of this is as follows.

If we say our array memory, location/address starts from 100, then the following integer address will start from 104(100+4) bytes, and so on.

In the above illustration/figure, we have an array with 6 elements in it, with a memory address pointed from 100 to 120. So theoretically, anything that we store after this array takes the address from 124.

Note: In Java, we have to specify the size of the array ahead of time before initializing the array.

We knew everything on the computer is stored in bits 0 or 1. Let us see how these array numbers from the above sketch are stored in memory and addressed in binary.

32-digit representation of array values whose mem-locations are from #100 till #120 (Contiguous memory locations)

Declaration and initialization

Consider an array A[] that has 5 elements. To access the last element of the array, we use A[4].

With this knowledge, if N is the array length, then (N-1) is how we access the last element. There are two ways we can declare and initialize the array in Java.

What happens if we declare an array as follows?

int[] A = new int[3]; 
// stores 3 items, capacity = 3 and size is 0(no items added, so far)

System.out.println(Arrays.toString(A)); // [0, 0, 0]

Initially, we did not add any items to the array, so the array values are defaulted to 0 as seen above.

Let us see another way where we declare and initialize the array.

// approach 1
int[] A = new int[5];

A[0] = 1;
A[1] = 2;
A[2] = 3;
A[3] = 4;
A[4] = 5;

// approach 2
int[] A = {1, 2, 3, 4, 5};

Arrays with char datatype and String class is as follows.

// String arrays
String[] fruits = new String[3]; // contains 3 strings

// char arrays
char[] chars = new char[256]; // contains 256 items

This small illustration helps you understand how we access array elements using their indexes.

How to access elements?

Following is a simple sketch of an array A with a capacity N.

int[] A;

Since arrays in Java starts from 0th index. If you want to access the first element, you need to give A[0], and A[1] for accessing the second element, and so on A[N-1] to access the last element.

What happens if we do A[-100], A[N], and A[N+1] ? 🤔

You guessed it. We run into ArrayIndexOutOfBoundsException.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 5
	at array.ArrayIntroduction.main(ArrayIntroduction.java:20)

At most, we can access the last element of the array using A[N-1].

How to print array elements

A simple snippet to print the array elements from 0 to (N-1) index.

public class PrintElements {
    public static void main(String[] args) {
        int[] A = {1, 2, 3, 4, 5};

        int N = A.length;
        
        for (int i = 0; i < N; i++) {
            System.out.println(A[i]);
        }
    }
}

The time and space complexity to print these array elements are:

Time complexity -  O(N) - We iterated over all the array elements of size N, so the time complexity is linear.

Space complexity - O(1) - No algorithmic memory is used here. We just used the input A[] memory, hence Constant time.  

Summary

So far, we covered the basics of array data structure. In computer science, arrays are the building blocks for many other, more complex data structures. In the next lesson, you will learn about the strengths, weaknesses, and more about arrays.

Data Structures and AlgorithmsArrays

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Leetcode 217: Contains Duplicate

This question marks the first problem when working on duplicate data, either integers or strings etc. Companies that have asked this in their coding interview are Amazon, Apple, Netflix, Google, Microsoft, Adobe, Facebook, and many more top tech companies. Problem statement Given an integer array nums, return true if any

Leetcode 217: Contains Duplicate
Members Public

Leetcode 121: Best Time To Buy and Sell Stock

The Best time to buy and sell stock problem is a classic problem that can be solved using the Greedy approach. This is one of the most popular questions asked in such interviews. Companies that have asked this in their coding interview are Facebook, Amazon, Apple, Netflix, Google, Microsoft, Adobe,

Leetcode 121: Best Time To Buy and Sell Stock
Members Public

Arrays From Zero To Mastery: A Complete Notes For Programmers

This article discusses array data structure with sketches, memory diagrams, array capacity vs. length, strengths & weaknesses, big-O complexities, and more!