Java Arrays in 5 Minutes

What is an array

An array is a grouping of the same typed values in computer memory. In Java, the data stored in an array can be a primitive or an object. As a quick refresher, primitive data types in Java are byte, short, int, long, float, double, or character. When storing primitives in an array Java stores these in adjacent blocks of memory. An element is an individual value in an array. The index is the location of an element in the array.

Creating an array

In Java, there are two ways to create an array. The first way is using the new keyword as shown below.

int[] array = new int[10];

The other way to create an array is using a shortcut syntax. The shortcut syntax allows us to instantiate the array with exactly the values we need. Using this syntax, we skip having to do the costly operation of looping through the array to insert an element at each index.

double[] array = {10.2, 15.4, 20.6, 25.8};

If you don't know the elements that you want to put in your array when you instantiate it go with the new keyword.

It's important to note that no matter how we create an array we need to know the size we want to allocate to the array. The indexes of the array are zero-indexed. If you have an array length of 10 the first element of this array will actually be at the index of 0 and the last index will be 9.

float[] array = new float[10]; 

Finding array length

Finding the length of an array is essential for using arrays. Without knowing the length of an array a programmer won't know when to stop looping through an array. Trying to access an index outside of the array, index 11 in an array of length 10 for example, results in an out of bounds exception in Java. Lucky for us arrays have a length property. The length property makes finding the array as easy as calling .length on your array. There are no parentheses as this is a property, not a function, on the array. The length is one based meaning in the example below our length would return 3 but the indexes in the array would be 0, 1, and 2.

int[] array = {22, 33, 44};
array.length

When first learning arrays in Java it can be easy to get tripped up on the length property being one based. Remember when trying to find where an array ends you will always want the length - 1.

measuring tape

Photo by Diana Polekhina on Unsplash

Java array utility class

Java includes a utility class. This class has many common array methods already programmed for you. College and high schools usually don't allow the use of this class. Most universities prefer students to learn algorithms in this class by hand first. It's still important to be aware of the array utility class. You'll see it used in almost every codebase outside of an academic setting. It can save a ton of time when you need to a complex operation on an array.

The array utility class has too many functions to go over. At a high level, the class provides sorting, searching, copying, equality, comparison, and much more. The methods provided are always efficient algorithms. Often there are several flavors of algorithms to pick from to achieve one goal. Using the utility class is as simple as importing it then calling Arrays.whatever().

import java.utils.Arrays

public class ArrayTest{
   public static void main(String args[]){
      int[] array = {1,2,3};
      Arrays.sort(array);
   }
}

When to use arrays

The strength of an array is accessing an element you know is in the array or accessing a specific index. This can run in big O(1) time, also called constant time. Accessing elements is the strength of an array. If you know something is in the array and you know where it is it's efficient to access that item. You don't have to spend any time or effort searching through the array, you can grab the element by using the index.

Arrays start to become a bad choice of data structure when you need to search, insert, or delete an item. Worst-case scenario, these operations tend to take big O(n) time, also called linear time. This is because you could have to go through the entire array for any of the operations. If you need to insert an element at index 0 in an array you'll have to move every element back one spot. Moving every element back one means you will have to go through every single element in the array. The same applies to deleting an element from the array.

Let's use a real-life example to understand the strengths and weaknesses of arrays. If you're running errands and you know you have to go to the post office. You know there is one nearby so you can go directly there. That errand is quick and simple since you know exactly where to go. You can throw it in your GPS and go straight there. If you need to mail a package but the post office won't accept your package then you'd need to search around for a new post office. What if you aren't even sure if a post office exists that will take your package? You may have to drive to every single post office in the city. Even then there's no guarantee you would ever find one that would accept our package.

post office

Photo by Magic Mary on Unsplash

Conclusion

Arrays are the fundamental data structures in computer science. You see them in all codebases. The upside of arrays in Java is that they are quick and easy to create and are a great way to access a known element. The downside is that they can be expensive to search, add, and delete from. You can instantiate arrays using the shortcut syntax with curly braces or the new keyword. Remember that you need to define the size of an array when creating it. If you're unsure of the size or need to know when to stop moving through an array you can use the array.length property to find the length. The length will be 1 based though, meaning you'll need to subtract one from it to find the number of elements in an array. Length 10 means indexes 0 to 9 in the array. Finally, don't forget about the Java Arrays utility class. It has everything you need to work with arrays already coded for you in an optimal way. Don't count on being able to use it in academia though. If you liked this post, learned something new, or just want to support my writings you can find more great writings on my blog, medium, or my Twitter. Thanks for reading!