Arrays

Contents

keyboard_tab

The course is part of this learning path

Arrays
Overview
Difficulty
Intermediate
Duration
57m
Students
97
Ratings
5/5
starstarstarstarstar
Description

This course covers the fundamentals of data structures specifically looking at the regular built-in arrays that Java provides as part of the language, as well as the ArrayList class, which lives in the java.util package.

Intended Audience

  • Beginner coders or anyone new to Java
  • Experienced Java programmers who want to maintain their Java knowledge
  • Developers looking to upskill for a project or career change
  • College students and anyone else studying Java

Prerequisites

This is a beginner-level course and can be taken by anyone with an interest in learning about Java.

Transcript

In this lecture, we will take a look at our very first data structure. At the most fundamental level, a data structure is just a collection of elements. In an array, the elements must be homogeneous or the same. For example, if I have an array of integers, all the elements will be integers. Or if I have an array of strings, they must all be strings, or more precisely, string references. An array can be visualized as in the diagram you see now, the array has a single name but it is divided into cells, each of which can hold a piece of data. The array must specify a data type to hold. Each cell within the array can then hold a piece of data with that data type, such as integer. The piece of data that lives in the cell in an array is called an element of the array.

The means by which we identify where an element lives in the array is by an element's index, the plural of which is indices or indexes. Arrays in  Java, as mentioned, can hold data at each index inside each cell of a specific type, but that type must be the same again, that's referred to as homogeneous elements. Additionally, when you declare an array in  Java, you use the new operator to allocate a particular size of array. The memory allocated by the new operator for an array will be contiguous, that is the cells that make up the array will be adjacent in memory.

So, let's take a look at an example so that we can understand how to work with arrays. I've created a project Section4-Projects in IntelliJ, which you can see here, and we're going to make an ArrayFun  Java class file. So, let me 'right' click the 'src', 'New',  'Java Class', and then ArrayFun, and that creates the ArrayFun  Java file. you don't really see the extension here, but that's what happens. That's the source file. And then we have of course public static void main(String[ ] args). I put my little comment there so you can see where main ends very easily. I'm going to create an array reference called myArray and we could do this all in one line just like any other variable for initialization. But in this case, I'm putting the declaration on one line. And now the initialization, myArray = new, and the syntax is a little bit different. You have to use the square brackets again right here, which we'll go over again in just a moment. And then I'll say myArray at 0 is 10, myArray at 1 is 22, myArray at 2 is, say 5. I'm just putting some integers in here. At 3 is 17, and then myArray at 4 is 20. There you go. So, that's how you access each individual index. And what we're going to do here, for int i = 0, i <, pay close attention here, myArray.length. The length, field.

Okay, here the for loops end. And again this is not required, these are just comments I put there to help you line everything up properly. System.out.println() We're going to see myArray at i, here we go. And of course, we've got the end of main in the end of the class. So, let's run this and see what it does, and then we'll talk more about it and review some of the facts that I went over. So, we right click this, and then we go to 'Run 'ArrayFun.main()'', and it does, in fact, after a couple of seconds bring up the output and we get the elements printed out one by one. Since the value of i is changing, it's going through printing them out one by one, 10, 22, 5, 17 and 20 as expected. Pretty cool. So again, you'll notice that the declaration of the array in Java is similar to any other variable declaration, except that we use the [ ] after the data type to tell the array what kind of type it holds in its cells. So, in this case we say it's an array of integers. So right here, the brackets here indicate it's an array rather than just a single integer. When you initialize an array, as we see in the following line right here. You specify the number of cells that the array is to have inside the brackets next to the data type of each of those cells.

An important note is that even though the cells themselves, in this case, hold integers which are primitives, the array itself is always a reference type. In other words, the array variable myArray will hold the address of the array, specifically the first byte of the array. Therefore, whether it's an array of primitives or references, the array itself is always a reference type. So, note that since we use the new operator with arrays in  Java, you could get the array size at runtime from the user or a file or some other source. This means that instead of a literal constant like 5, like we're using right there, you could use a symbolic constant with the final keyword, or even a variable or value returning method call, essentially anything that resolves to a value. However, once the array is created, you cannot directly resize it, it is fixed in size. So, that's another key point about arrays. Once created, the array object knows its own length, which you can see right here. And that can be accessed via the public constant, appropriately named length, as you see in the for loop. When accessing the elements, whether to store values, which you see in the code above the loop or retrieve values which you see inside the for loop, you use the bracket notation with a value. Or again, anything that could be resolved to a value, like the variable i in the for loop. Note that the highest valid index of the array is one less than the length.

So, since our array is size 5, the highest valid index is 4. This is because the first index is 0, we count from zero a lot in computer science and arrays are no exception. You saw that with loops, we often start at zero and go up to strictly less than something else, and in this case, it's less than 5. So, that means it will stop. Since we're using integers, it'll stop at 4. So, if we change the upper bound of the for loop to include the 5. So, if I put a little = sign there instead of the < sign. So, it's <= now. And let's see what happens if we run this. So, the src, right click, run it again. All right, there you go. So, you see we have an error in the code. It even tells us what line. It says it's on line 14 something squirrely happened, or at least it thinks that's where the error is. And in this case, it's right. So, it tells you what the error is, this time it's pretty clear. Index 5 is out of bounds for length 5. So, if it's length 6, index 5 would be okay. But since our arrays is length 5, index 4 is the highest index. So, we get the special type of exception which gives us information about an error occurring ArrayIndexOutOfBoundsException. So, an exception is said to be thrown when an error occurs at runtime. In this case, we don't own the memory out of bounds in the array at Index 5, our array only covers the memory from indices through 4 inclusive. So, this is a common problem in our syntax called an off by one error, which leads to the fatal runtime error, resulting in our program crashing and us getting this exception.

So, we definitely don't want that. So, let's change the code back. That'll make it even worse, okay. So, now there's an alternative syntax that you should be aware of for the for loop that works with collections like arrays. It's called the enhanced for loop. So, let's check this out. So, I'm going to comment this out right here. And you could do it manually, but I do control or command on Mac, it's Ctrl on Windows. Forward slash, and right here, watch how the syntax is different. int num : myArray. And then we're going to put System.out.println, and then put num in there. And of course, let's run it again. So, 'right click', 'Run'. So, we get the exact same thing that we got before, all the elements that are in our array. Pretty cool. So, behaves the same as far as the output is concerned, but notice that the only reason the variable num, in this case, is an integer is because the elements in this array are integers. So, if it had been an array of strings or floats or doubles, we would use that instead with the enhanced for loop. With the regular for loop on the other hand, we always use int because we're talking about indices, the plural of index, and that's always integers, right? So, this is always going to be an int. But here it has to do with the type of the data in the array, not the index. So, this avoids the array index out of bounds exception, because you can't go out of bounds if you use the enhanced for loop.

So, some people really like it for just printing out elements inside of say an array or other container. Before we move on, I'd like to issue you a challenge. So, create a file named MoreArrayFun and use a regular for loop to populate the array of integers of size 10 with the numbers 1 through 10 inside of it. So, that should make it a lot shorter than doing it by hand. So, when we populated our elements, we did kind of semi-random elements here, and then populated it one by one. But with yours, you're going to use a loop and look at what we did here for print out for output, but you're going to take advantage of some of the code we've seen and you're going to populate it with the numbers 1 through 10. So, you're still starting at index 0 going up to 9 in this case, because it's a size 10 array. But the numbers at each index will be 1 through 10. Then in a separate enhanced for loop below where you populate it, I want you to print out the elements of the array that you just populated. So, pause the video, and come back when you're done or if you need some help. How did that go for you? Were you able to complete this challenge? This one combines your knowledge of repetition control statements and your newfound skills using arrays. Let's work on it together and see what we come up with. So, let's create the, we can close this one, will create the MoreArrayFun. We're all about fun in this class, right? So, let's see here. public static void main. And we'll make our array. This time I'm going to do it on one line but you can do it on two separate lines, doesn't really matter. But we need size 10, not size 5 this time. We want to populate it with a regular old array. That wasn't cool. Okay, there we go. And myArray at i, and now if we're really careful here, we know that i was going to go from 0 to 9. And we need that for the index, but we can set this equal to i + 1. And if you think about it, that makes a lot of sense. So, i = 0, it will be 0 + 1, which is 1. And when it iterates it'll be i = 1, at index 1 it'll be 1 + 1 which is 2, etc. All the way up to index 9, which would be 9 + 1 that's 10. So, that's pretty quick and pretty cool. So, we could put an int for, but I'll just spare it, for now, spare you for now. And here's our enhanced for loop. And we will print out our number. And of course let's run it. Sorry, I need a dot there. Right-click, 'Run', and there we go. We've got numbers 1 through 10 and to just 1 through 10 printed out. Nice work. So, it prints out exactly what we expected and flawlessly. Arrays are the most fundamental data structure in  Java. So, it's extremely important to know how to use them. In the next lecture, we'll look at a more complex data structure that behaves a lot like an array, but it resizes when necessary. It's called the ArrayList. Let's get going.

 

About the Author
Students
759
Courses
20
Learning Paths
4

John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.

Covered Topics