Java for Humans {Data Structures: Arrays}

Lincoln W Daniel
Jan 18, 2016 · 8 min read
View Table of Contents | Download Supporting Code | Subscribe to ModernNerd Youtube Channel for Coding Videos | By Lincoln W Daniel

In your phone, you have a phone book filled with names and numbers of family and friends. The good thing about your phone book is it holds many contacts, but the bad is that it is limited, although you may not know it. Your phone book can only hold a predetermined number of contacts. You can add new contacts, update contacts, and delete contacts. With that said, your phone book is a data structure. More specifically, it is an array. We will learn how to make a phone book with an array in this chapter.

Why Arrays are Important & Useful

In the Variables chapter, you learned how to store a single data point in a variable. Then, in the Datatypes chapter, you learned that its best to store data of a certain type in a variable with that respective type: store a character string in a String variable, store a whole number, integer in an int variable, store a floating point number in a double variable, and so on. Now that we are becoming more advanced Java programmers, we want to store a collection of data in a single data structure for later manipulation.

Data Structures

A data structure is exactly what it sounds like — a structure that holds data. Unlike variables, which only hold a single point of data, data structures collect one or more points of data of the same type. Although a data structure can hold many points of data, a data structure, itself, is only a single object that can be stored in a variable like any other datatype. A data structure’s type becomes the type of the data points it holds. For that reason, a data structure is sometimes referred to as a container object, or a collection. Some data structures can expand infinitely in size, but others, like arrays have a fixed size.

Arrays

An array is a data structure that holds a fixed number of values (data points) of the same type. Each item, or value, in an array is called an element, and each element is accessed by its integer index. When we initialize an array, we get to choose what type of data it can hold and how many elements it can hold.

The number of elements an array instance can hold is stored in its final int field called length. A final field cannot be changed after it is set, and therefore, a final field is often referred to as a constant field. This length property of the array is what allows it to be of a fixed size.

We initialize an array instance like we initialize an instance of any other object in Java. The difference with arrays is that next to the type of array, we add a set of empty opening and closing brackets. Further, at the end of the initialization,we put the number of elements the array can hold inside a set of opening and closing brackets. There a few other ways to initialize arrays, but this is the most popular and flexible way. Let’s initialize an array of strings to hold the names of our five friends:

String[] friends = new String[5];

In that code snippet, we created an array called friends to hold a maximum of five String values — the names of our friends. Now that we have our array instance, we can access each element of the array by accessing its index in the array. Because indices in Java are zero-based, the first element in an array is stored at index zero (0) and the last element is at index of one less than the length of the array. Therefore, if we want to access our first friend, we would access index 0.

At initialization, all elements in in the array are initialized to a zero value: null for arrays of objects, 0 for primitive number types, and false for boolean types. Let’s add our friends to the array before we try to get them out:

friends[0] = "Imani";
friends[1] = "Andres";
friends[2] = "Keith";
friends[3] = "Sasha";
friends[4] = "Tabitha";

Now that we have added our five friends to our friends array, let’s access the first and last one and print them out:

String firstFriend = friends[0];
System.out.println("First friend is " + firstFriend);
//prints "First friend is Imani"
System.out.println("Last friend is " + friends[friends.length - 1]);
//prints "Last friend is Tabitha"

Notice that we were able to access the last element in our friends array by doing a little math. We used the length property of the array to get the total number of elements in it array and subtracted one from that number to get the index of the last element. That is the dynamic way of accessing the last element, but we could have just as easily typed friends[4] to access the fifth (last) element in our array of five friends. In the unfortunate event that we lose a friend, we should zero out the value of the element in our array that corresponds to our lost friend. If we lose our first friend and our second friend changes her name, we can reflect those updates in our array like so:

friends[0] = null;
friends[1] = "Alejandro";
System.out.println("First friend is now " + friends[0]);
//prints "First friend is now null"
System.out.println("Second friend changed name to " + friends[1]);
//prints "Second friend changed name to Alejandro"

Now our first friend equals null and our second friend, Andres, changed his name to Alejandro. Let’s make another array to hold the corresponding phone numbers of all our friends as integers:

int[] friendsPhoneNumbers = new int[friends.length];
friendsPhoneNumbers[0] = 555_8000;
friendsPhoneNumbers[1] = 5554448;
friendsPhoneNumbers[2] = 555_4311;
friendsPhoneNumbers[3] = 555_7898;
friendsPhoneNumbers[4] = 555_6710;

Our friendsPhoneNumbers array is initialized with the value of the length property of our friends array to ensure they both have the same number of elements.

Notice that some of the phone numbers have underscores in them. Using underscores in long numbers, like commas on paper, make them easier to read. You can add underscores between numbers, not at the start nor end.

We can loop over, or traverse, our array of friends to print out the name of each of our friends by using a for loop terminated by the length of our array:

for(int index = 0; index < friends.length; index++) {
System.out.printf("Friend %d: %s\n", index, friends[index]);
}
/*Prints:
Friend 0: null
Friend 1: Alejandro
Friend 2: Keith
Friend 3: Sasha
Friend 4: Tabitha
*/

We can go even further and print out each friend’s phone number from our friendsPhoneNumbers array next to his/her name. However, we should only print a friend’s phone number if their name is not equal to (!=) null:

for(int index = 0; index < friends.length; index++) {
String friend = friends[index];
if(friend != null) {
System.out.printf("Friend %d: %s's phone number is %d\n",
index, friend, friendsPhoneNumbers[index]);
} else {
System.out.println("#Alert: No friend at index " + index);
}
}
/*Prints:
#Alert: No friend at index 0
Index 1: Alejandro's phone number is 5554448
Index 2: Keith's phone number is
5554311
Index 3: Sasha's phone number is 5557898
Index 4: Tabitha's phone number is 5556710
*/

Notice that we don’t print the element at index 0 in either array because we lost our first friend earlier; the element at index 0 in the friends array is now null, so the corresponding phone number at index 0 in the friendsPhoneNumbers array is now useless to us. One more thing we can do to make our phone book more intuitive is consolidate our two arrays into one. The new array will hold Friend objects instead of String and int values.

Remember that, by default, all classes extend the Object class provided by Java. The toString() instance method of the Object class is called whenever the compiler tries to convert an object to a String.

Our Friend class will have three instance fields: name, areaCode, and phoneNumber. Our Friend class will override the toString() instance method of its Object superclass to return all of a Friend instance’s information as a single String instance:

public class Friend {
private String name;
private int phoneNumber;
private int areaCode;

...
@Override
public String toString() {
return String.format("Name: %s | Phone Number: (%d)-%d",
name, areaCode, phoneNumber);
}
}

In that snippet, we used the format() static method of the String class to map values to placeholders in our String.

Let’s create an array of type Friend to hold all of our friends’ contact information like a phone book does.

Friend[] phoneBook = new Friend[5];
phoneBook[0] = new Friend("Imani", 215, 555_8000);
phoneBook[1] = new Friend("Andres", 484, 5554448);
phoneBook[2] = new Friend("Keith", 319, 555_4311);
phoneBook[3] = new Friend("Sasha", 212, 555_7898);
phoneBook[4] = new Friend("Tabitha", 212, 555_6710);

Our friend, Imani, from earlier decided to give us another chance, so we added her to our phone book in her original spot, index 0. Now, we can more intuitively loop over our phone book array to print out each of our friends and their contact information:

for(int index = 0; index < friends.length; index++) {
Friend friend = phoneBook[index];
if(friend != null) {
System.out.println("Friend " + index + " -> " + friend);
}
}
/*Prints:
Friend 0 -> Name: Imani | Phone Number: (215)-5558000
Friend 1 -> Name: Andres | Phone Number: (484)-5554448
Friend 2 -> Name: Keith | Phone Number: (319)-5554311
Friend 3 -> Name: Sasha | Phone Number: (212)-5557898
Friend 4 -> Name: Tabitha | Phone Number: (212)-5556710
*/

The last thing you should know about arrays holding objects is that when you want to update an element at an index, you don’t need to update the entire element. You can simply get the element and update the field you need to update or call the method you want on the object. Let’s change our second friend’s name from Andres to Alejandro again and print it out:

Friend friend2 = phoneBook[1];
friend2.changeName("Alejandro");
System.out.println(friend2);
//prints "Name: Alejandro | Phone Number: (484)-5554448"

If we lose our friend, Imani, again, we can remove her from our phone book array the same way we did earlier in our friends array:

phoneBook[0] = null;
System.out.println(phoneBook[0]);
//prints "null"

That’s it. We now have a phone book we can add to, update the elements of when a friend changes his or her contact information, and delete elements from when we lose a friend. It is clear that arrays are useful when you want to store a collection of values — objects or primitives — of the same type in one place for later use. The only constraint is that an array must have a fixed length of elements. In the next chapter, we will learn about lists which can dynamically expand in capacity when necessary.


ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel

Written by

My passion is in developing software to enable people to accomplish their goals more efficiently. Author @JavaForHumans.com. Creator of @Smedian.com

ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade