Arrays are a very powerful data structure used for a variety of purposes. The main purpose of an array is store a collection of information in a single place. For example, you might store a list of people to represent students in a classroom.

Specific items in an array can be retrieved by an index value, starting at 0. Each element of an array must be of the same type.

Declaring Arrays

In Java, there are two main ways to declare an array. The first way is to declare an array with a specific set of values.

String[] strArr = {"hello", "this", "is", "a", "predefined", "array"};

Another way to declare arrays is to declare an array with a length and a set of empty values.

int[] intArr = new int[5];

This would declare an array of length 5, with all values being 0.1

Accessing Indexes

In Java, you can access arrays by index using a simple syntax: arr[n], where arr is the array you would like to access and n is the index.

For example strArr[3] would give you a, since indexes start counting at 0.

0-Indexing (for advanced readers)

Zero indexing in Java comes from the C programming language2 (which Java is partly inspired by), where arrays are essentially just a pointer to a block of memory. C also allows you to access specific memory addresses and allows memory address arithmetic, which means you can add integers to memory pointers to access other memory pointers.

For example, a memory pointer to address 10003 could be the start of an array, and you might want to access the memory address with an offset of 4. This could be done by incrementing the pointer by 4 like ptr + 4.4 If arrays started counting at 1, there would be quite a few more -1s in your code since you would need to constantly subtract one to offset the fact that you start counting at one instead.

You can see the illustration of this problem in the below diagram:

Array Indexing

Modifying Arrays

Similar to accessing arrays, you can modify array elements by index using the same syntax: arr[n] = 10 would set the value at n to 10. You can do any operation you would like on array elements. Think of array elements like a separate variable that you can modify: any changes you do them gets “saved” into the array.

⚠️ Array Warnings

Arrays are fixed size, which means that you cannot resize an array without making a new one and copying the data over (if you would like automatically resizing, see the tutorial below on ArrayLists).

When passing arrays into functions, any modifications to that array will be reflected in the original. This means that following piece of code:

int[] arr = {10, 41, 29, 299};
sort(arr); // sorts the array in ascending order.
for (int i = 0; i < arr.length; i++) {
	System.out.print(arr[i] + " ");
}

…would print 10 29 41 299.

This is sometimes useful, but when you want to avoid this behavior, you can create a new array and copy the elements over.

ArrayLists

An ArrayList is like an array, but it allows you much more powerful operations like inserting, appending and deleting elements. ArrayList is a class5 that implements the List interface.6

Before using ArrayLists, you must first import it by adding the following lines to the top of your code:

import java.util.ArrayList;
import java.util.List;

or

import java.util.*;

Creating ArrayLists

You can create an ArrayList with the below syntax:

List<Integer> lst = new ArrayList<Integer>();

There two main things to notice in that code snippet:

  1. I declare a generic List type rather than an ArrayList

    In Java, it is best practice to declare an ArrayList and use automatic up-casting6 to the List interface.

  2. I declare it with the Integer class rather than int primitive

    It is not possible to declare an ArrayList with primitives. With the autoboxing feature of the modern JVM, it doesn’t affect code much.

Accessing Elements

Accessing elements in an ArrayList can be done using the get(int index) method, which returns the value of the element at index index. To get the value of the fourth element (0-indexed) of an ArrayList, you would call lst.get(4).

Note that you cannot modify the element7 using this method.

Adding Elements

Adding elements in an ArrayList can be achieved by using the add(Object o) or add(int index, Object element) method. The fist method appends the element to the end of the list, while the second adds the element at index index.

For example:

List<String> lst = new ArrayList<String>();
lst.add("hello");
lst.add("foo");
lst.add("bar");
// lst contains {"hello", "foo", "bar"}
lst.add(1, "mr. ");
// lst now contains {"hello", "mr.", "foo", "bar"}

Modifying Elements

Modifying elements can be achieved using the set(int index, E element) method, which sets the value of index index to element.

As a continuation of the previous example,

lst.set(2, "bar");
// lst now contains {"hello", "mr.", "bar", "bar"}

Deleting Elements

Deleting elements can be done using the remove(index i) or remove(Object o) methods. The first method removes the element at index i, while the second removes the object o from the ArrayList.

As a continuation of the previous example,

lst.remove(2);
// lst now contains {"hello", "mr.", "bar"}
lst.remove("hello");
// lst now contains {"mr.", "bar"}

Next Step

After learning about arrays and ArrayLists in Java, you should read my tutorial on array algorithms.

Footnotes

  1. When declaring a primitive variable without a value, it will default to the equivalent to 0 of that type (e.g. for doubles, it would be 0.0, for booleans it would be false). 

  2. C’s zero indexing likely was inspired by BCPL, a precursor to C. 

  3. Memory addresses are generally represented in hexadecimal, but for simplicity, let’s just use base 10 instead. 

  4. It is actually significantly more complicated than this, if you would like to learn about pointers in C/C++, here is a great resource. 

  5. In Java, array classes are created during runtime by JVM. ArrayList, meanwhile is an explicit class defined in Java source code. 

  6. See the part two of my tutorial on Object Orientated Programming  2

  7. You can modify the object contained in the element if that object is mutable see part two of my tutorial on OOP.