Practice Exams:

1z0-808 Oracle Java SE 8 Programmer – Arrays part 1

  1. Section Overview

In this section, we’re going to begin our discussion about different kinds of collections. And we’re going to look at one of the most basic forms of collection, which is called an Array. So an Array is just a way for us to take a bunch of related things, put them all together and store them in memory, volatile memory. That is, memory that could be erased if the program shuts down. But while we’re working with our program, we’re going to need to access data. And this is a great way to create a collection and keep it all together. So let’s look at our first lecture on a race.

  1. Arrays

An array is an object. And what it does is it represents a collection of other objects. And there are rules for the objects that it represents. They all have to be homogeneous, they all have to be of the same type. And they’ll be organized in a collection that has integers, so they’re indexed by their integers. In other words, the first object that’s put in an array has an index of zero. The next one has an index of one and so on. The way that we work with arrays is they’re pretty similar to other objects, although they’re slightly different syntax. But like other objects, we’re going to declare an array reference. We’ll instantiate the array with the new keyword.

But normally once we create an object, we go in and we initialize all of the different instance variables. With this, we don’t really have instance variables, we have elements. So we go into the array and we populate each element in the array. And I will tell you, one of the most common bugs when you’re first working with arrays is to forget that, to think that you’ve made an array of say, my date objects, you’ll forget that you also have to create the My date objects that go inside of the array. So let’s look at the syntax. When we looked at the main method, I showed you that there was a number of different ways that you could use the square brackets.

You could put the square back brackets to the right of the type, you could put the square brackets to the right of the identifier. Square brackets are what we use to say this is an array. And both of these syntaxes are completely legal. And given that there’s only one variable here, there’s really no difference between the two. But with that said, the first one is much more common. In Java, you typically put the array syntax, the square brackets to the right of the type and it’s just easier to see. If I look at this, I can say, oh, this is an int array. If I look at the second one, I think it’s an int. And then I don’t discover that it’s array unless I go through the whole name.

But syntactically, they’re the same. The only time there’s a difference is if you’re declaring more than one array in a single line of code. So if we have this first line here, we’re creating two char arrays, char array one and char array two. The second one is different. We’re creating char variables. The first variable is a char array called char ray three. The second variable is just a char. So when you do have more than one variable declaration on a line, the placement of those square brackets does matter. It does impact the definition. So let’s create an array and see how this works. You’re going to use the new keyword, but we’re also going to have to set a size. So this is the way it works.

On the left side we’ve declared our int array variable and on the right side we say new, we say the type. And then you don’t use parentheses, you use square brackets. The number inside of here, that’s going to be the size of the array. Now we’ve said here that there are going to be ten elements in this array but when they’re organized they’re going to be index based. They’re starting with the number zero. So we’d have the number zero through nine in terms of what index does each int live. After we’ve instantiated the array, the next job is to populate the elements of the array. Now the first thing that’s going to happen is the new keyword is going to cause all of the elements to be filled with a default value.

If you remember we talked about default values, for instance variables. We said that anything that is type object would be null, anything that’s type int would be zero and so on. So when we go through this we say new int ten, we’re going to get an index, sorry, we’re going to get an array that has elements zero through nine. And if we looked in each of those indexes zero through nine we’d see that every int has been set to zero. So now we’re going to go through and actually change that. We’re going to grab integrate at index zero and set it to one. We’re going to grab inte at index one and set it to two and so on. Now one of the mistakes that you could make is you could try to set intra at ten.

Remember that the indexes are always going to start at zero. So if we’ve said that we’ve got an int array that has ten elements, then the indexes will go from zero to nine. If you try to set this to ten it’ll actually compile. But at runtime you’ll get an array index out of bounds exception. Arrays also have a special syntax that allows us to instantiate and define and assign all in one step. It’s these curly braces right here. So on the left side you define your int array variable. On the right side you use the curly braces and then just add all the values that you want and it’ll figure out how big to make the array and it’ll put each of these values in the right indexed element.

So this one will be added to the zero index. This two will be added to the first index. This ten will be added to the nine index. And in any case it counts it and says there are ten elements. So the array is going to be of length ten. There are some rules for the syntax. It’s only allowed when you first declare the array initially and specifically it has to all be in the same statement. In this example we’ve got two different statements. So I’ve got the int array that I’ve defined and a semicolon, which makes it the end of that statement. And then I’m taking the in array and I’m trying to assign the literal value. That’s illegal, you just can’t do it. So an array holds a bunch of elements, but it also holds a piece of state.

And that state is its length. We can access the length by using the dot operator. So my array dot length, in this case it would return three because there are three elements in this array. One of the gotchas here is that the length of an array is a read only attribute. You cannot set the length and we typically use this length element to iterate through all of the members of the array. So here’s an example of doing just that. We could iterate through any kind of a loop. It’s usually done with a for loop. So here I’ve got an int array that has ten elements. I’m using the four loop and I’m using that length property right here to figure out how far should I go.

So we’re starting at zero and we’re going all the way until we’re less than as long as we’re less than the array dot length. So as long as we’re less than ten. And that makes sense that we’re doing less than because we’re starting with zero, not one. So we’re going from zero to nine as opposed to one through ten. Now the rest of this they’re just going through and multiplying the current index of J and then assigning that to the current element. So element zero would be zero, element one would be one, element two would be four, and so on. So that length property is read only. You can’t change it. In fact, the entire array is fixed in length. You can’t resize an array.

If I create an array and I try to say array length, I know you were ten, but now I want to set you to eleven. It won’t even compile. That is illegal. Now, although an array can’t be resized, there is a method in the system class that will allow you to create a brand new array and copy all the elements from the old one into the new array. And of course, this is just one method that system class provides. It’s called array copy. I should note that although we are seeing this method in the system class, that a lot of the helper methods for arrays is actually in a class called arrays, which we’ll take a look at a little bit later. So here’s an example of using array copy.

I have my initial array which has three elements, and for some reason now I’ve decided I need the array to actually have four elements. So I’m creating a temporary array. At this moment, they’re both pointing to the same array. Then what I’m doing is I’m creating a brand new array that is going to have four elements and we use the system array copy to copy all the old elements into the new array. So it starts with what is the array we’re copying from what is the index we’re starting at what is the array we’re copying to what index are we starting at and how far should we go? So that’s the system array copy method. So far, all of the arrays that we’ve looked at have been storing primitives, but they can also store Java object types as well.

So here’s an example of creating a My Date array. So new my date three. That it’ll. Store three my dates. Once again, the biggest mistake that people will make is thinking I just created three new My Date objects. It looks similar enough to creating a My Date, right? It almost looks like the parentheses. We got the square brackets, but what it’s really doing is creating three element slots in the array and they are all holding null at this point. That’s the default, it’s holding null. So we have to populate it. We create a new My Date, assign it to date zero, create a new My Date, assign it to dates one, to dates two, and so on. By the way, this act of passing in an index to the dates is known as subscripting.

We could use the inline initialization syntax with objects as well. So here’s the curly braces and I would just comma separate all of my new My dates. Here’s another example. We could do it with strings as well. So here are a whole bunch of strings which are being created and added to a string array. And of course, you’ve already encountered one array of strings. That’s the main method. It takes an array of string as its only parameter. We usually call it Args, but we really haven’t explained why we have it. And the reason that Args is there is it’ll take anything that’s passed in from the command line or when we start our application and it will pass in that text as arguments. So, for example, let’s say I’ve got, let’s look down below here first.

So I’m going to write Java foo, which is the name of the program, and then two words hello and World. And what’s going to happen is when this main method is executed, hello is going to be added to the array of strings at index zero. World is going to be added at index one, and so we can then iterate through and grab all those different words out. So why do they have that? Well, you can imagine that maybe we have a Java foo debug and we look for the word debug, and if that word debug is there, then maybe we add some logging code or our code is a little bit more verbose when it shows error messages, things like that. So it’s a way for us to pass in a command from the command line into our application.

  1. Polymorphism Revisited

So arrays behave lot like other variables in that whenever we declare an array we’re going to specify what is its type. And we’re not just specifying that we’ll hold that type, we’re specifying we’ll hold that type and any subtype. If it’s an interface type, we’re saying we’ll hold that anything that implements that interface type. So polymorphism is at work with an array as well. Let’s take a look. Imagine we have this hierarchy. We’ve got a person on top and we’ve got an employee extends person, secretary, manager extends employee. If we take a look at the code, look like this. Notice that the person has a name and a date of birth. Employee adds a salary and an implementation of two string.

Manager has a department and has yet another implementation of two string. And secretary also extends employee. But it’s not adding anything. No salary, no department, it’s not overriding two string and so on. Now you may have noticed that everything listed there was using the public attribute instead of using encapsulation. That was just done to make this a very simple example. In real world code, we want to do encapsulation, make those fields private. Now let’s revisit polymorphism. So with polymorphism I can have a reference variable of employee e. And what that is saying is I can accept any employee objects and any subtypes including manager and secretary.

Of course we’ve seen this before, but now we’re going to apply it to an array. And what we can do is we can create secretary and manager objects and we can store them in an employee array. So it looked like this. We create our employee array. On the left side we’re defining the employee variable staff. And on the right side this is where we’re defining how many employees it’ll store. It’ll store three employees. So for the first element, staff zero, we’re just going to create a brand new employee and then we’re going to set the name of that employee. So in order to grab the employee that’s in the array, in index zero we use subscripting. We say staff bracket zero to grab a hold of that employee.

And then we can use the name property and set that name to be James. The next one we’re going to add in index one is we’re going to add a new secretary and once again we can grab the secretary using the subscripting syntax, set its name in this case to moneypenny and finally staff too. We’re adding a new manager and we’re setting the name to Miles. So as you can see, an array is polymorphic. We can substitute one object for another provided they’re all of the same type. We declared that the array was of type employee but that meant we could pass in an employee, a secretary and a manager. One thing to note is that when we reference one of the employees in the array using the subscripting, like we’re doing here, we’re referring to whatever object is in staff zero.

That reference is going to be of type employee. So the thing is we are limited to sending messages to whatever is available to an employee. Now name was declared an employee so that is available. What if I wanted to change it and I wanted to add something like the department? Well, I’m not going to be able to just reference staff two and change department because department is not available to employee. And even though staff two is a manager, just like when you set a new manager to employee, as we’re seeing on the top here, then the only thing that I can do is I can say let’s call methods that are available to employee and let’s look at and set variables that are available to an employee.

I can’t grab anything that was defined in a manager without casting and it’s the same thing with an array. So if I want to change the department I’m going to have to reference staff two which is the manager, cast it to be a manager. We place the entire casting operation in a set of parentheses to ensure that it happens first and then I can change the department to be Mi six. So after we’ve created this array now we can go in and print out all the employees name and we can do this with a traditional for loop. I could go in and just create a for loop that says int j equals zero j is less than the staff dot length and then keep incrementing j.

And then all we’d have to do is grab staff j which would start with zero, go to one, go to two and call the twostring method on it so that we could print out the employee’s names or we could do this with another kind of loop. This is one we have not seen before. This is the for each loop. Now even though it’s called a for each loop you don’t actually write the word each, you just say four. And in the parentheses there are two parts, a left side and a right side and they are separated with a colon. Now the right side is the collection. What is the collection that we’re going to iterate through? And the left side is a variable that we’ll use in the body of this for loop. So it’s going to iterate through all of the different elements in staff one by one.

It’s going to take the current element of staff and temporarily store it in an employee variable and then we can just simply say employee two string. So that’s a nice simplified syntax to be able to loop through an entire collection. Now, because of polymorphism, because of the ability to override methods, what’s printed out by calling two string depends on what the actual object is. So like for example, the manager class had overridden the two string. So that’s going to be a little different than secretary or employee. As we run through all of the different employees, we would see James for the first, money’s Petty for the second, and then Miles manages Mi six for the third.

By the way, that call to two string that we’ve been doing, that’s actually redundant. We don’t need to do it. And the reason is that if we walked through the print line method and we saw what happens when we just pass in an object, we’d see that eventually that method is going to call twostring. So you can certainly say twostring if you’d like, but it’s not really not recommended, it’s not required. So in these examples, you can see that we are iterating through the entire staff array and just passing in, you know, the staff element itself. In this case, here we are passing in the employee. And so it’s just not necessary to call two string.