What are Java Arrays?

As I’ve mentioned before, you can think of an Array like a bunch of variables all smashed together under the same variable’s name. So, as an example, you have a bunch of contacts in an address book, and instead of creating variables to represent each contact like so:

String contact1, contact2, contact3, contact4 //etc...

String contact1, contact2, contact3, contact4 //etc...

You can combine them all into one variable’s name like so:

List<String> contacts =new ArrayList<String>();

List<String> contacts = new ArrayList<String>();

Now, this code is for an ArrayList, which for me, is used heavily in my day to day programming endeavours. But this is in fact just a flavour of Java Arrays as it’s based on a Java List. So allow me to introduce you to the original Java Array.

String[] contacts =newString[10];

String[] contacts = new String[10];

Okay, so, two things you’ll notice:
1) The square brackets []
2) We’ve put the number 10 in there

The square brackets [] are Java’s notation for an Array. They just signify that the variable type (in our example, String) will not be just a single variable, but an Array of those variables. So this means that you could throw those square brackets next to any variable type in Java to make them an Array (I’m trying to think of a variable type in Java where that wouldn’t work, but I’m drawing a blank, so if there are any programmers out there reading this that know an example where this statement is false, please leave a comment).

Now let’s talk about why I put the number 10 in that code. Well, one difference between an ArrayList (think no square brackets needed) and an Array (think square brackets needed), is that with an Array, you’ll need to define the size of the Array when it’s being initialized. What do I mean by that? Here’s an example of code that would fail:

String[] contacts;System.out.println(contacts[1]);// this will give you an error

String[] contacts;
System.out.println(contacts[1]); // this will give you an error

The reason why this fails is because you haven’t initialized the Array. So let’s re-write this code with the initialization part included:

This will now work, but, you won’t see anything displayed in your console, because although you’ve initialized the Array, you haven’t yet actually populated it with anything. So how about we populate it with stuff? I want to keep this example simple, so I’m going to use a loop to populate the Array:

So what we’ve done here is initialized the Array with a size of 10 and we’ve created a “for loop” that will iterate over each element in the Array and populate it with something. In our case, we’re iterating over the “for loop” 10 times, as the “for loop” is based on the size of the Array (which is 10 elements in length). And for each iteration, we are storing the String “person” followed by the index of the current iteration of the “for loop”. Sound complicated, but here’s the output:
person0
person1
person2
person3
person4
person5
person6
person7
person8
person9

The word “person” is followed by the current index of the Array, 10 times. So wait a sec, why did the loop start with person0 and not person1? You were expecting to see the numbers 1 through 10 right? Well, that happened for two reasons. The main reason it starts at zero is because my “for loop” was coded to start at 0 and run 10 times (i.e. 0 -> 9), but I did that for a reason. The reason I did it is because Java uses a zero based numbering system for its Arrays. So when you want to refer to the FIRST element in an array, you use the number 0. The second element would be index 1, the third would be index 2, and so on. Had I programmed my “for loop” to start from index 1 and go until index 10, we would have seen an error when it tried to output the last element in the Array, because element at index 10 doesn’t exist! Only elements 0 -> 9 exist. Make sense? Hopefully it does, if it doesn’t just leave a comment below and I’ll try to re-word it 🙂

One neat thing I’d like to point out about Arrays, is that you can have something called a multi-dimensional Array. Now, having seen these in real world coding scenarios, they are a pain in the butt to understand and debug, so I wouldn’t recommend using them unless you put plenty of comments in your code describing its purpose. But for the sake of completion, I’ll show you how to use them. Let’s say you wanted to create a crossword puzzle program.

Example:
A D L E
Q N N O
W I N D
V K N E

Here we have a 4×4 multi-dimensional Array. The code to create this crossword puzzle would look like:

Now, having explained what an Array is in Java, I’d like to go back to what I mentioned before about the ArrayList. I find that the ArrayList is more useful in most coding situations, it has built in methods that allow you to do things like adding and removing elements without having to worry about the size of the Array (as it will grow and shrink as necessary). But, it is however, important to know what an Array is in Java and what the syntax looks like.

Well if you don’t mind, I’ll be leaving comments comparing my C++ knowledge to what I see here about Java.

So this bit of code:for (int i=0; i < contacts.length; i++)
Where did contacts.length come from? In C++ the structure would have been very different, like somefunction(contacts[]) or something. But what I see here is similar to invoking a public member function of a class using an object of that class. But the string array "contacts" isn't an object of a class, or is it different in Java?

Trevor, if there is no problem for you, let me answer to this question with my little knowledge about arrays!

You asked where does this “contacts.length” come from!
I don’t know about C++, but in Java, arrays are smart, they can do thing, they are objects, and of course they have methods while they are objects, right ?!
In this case, when you say:
String[] contacts = new String[10]
You have created an object that holds 10 elements, each of which is a String variable!
And we know that now we can invoke methods that are in the class from which the object is initialized;
In this case we invoke the method “.length” and it returns the number of elements in that array variable – contacts!

First of all, thank you for this wonderful free service. You’ve made the wrinkle that forms in the middle of my forehead loosen a bit. But yes, I’ll bite and be the one who doesn’t get it. Does index ten not exist because indexes can’t have two digits?

No worries about not getting it, let me explain using another example. First let me stress that Java array indexes are zero based. This means that the first number in the “series” of numbers will start with the number zero. So if you have 10 elements, you would count them out like this:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

So, zero to nine (0 – 9) is actually ten (10) numbers in total (i.e. 10 elements). So the reason why the element at index 10 doesn’t exist isn’t because you can’t have a two digit index, but because there are only elements 0 -> 9.

Let’s say we have an array of length 13, the index is still zero based, and this would mean the elements would be numbered from 0 -> 12. Because again, if you count out zero to twelve, you will have counted 13 numbers (which is the size of the array) 🙂

An array can have a MASSIVE amount of elements, to be exact I think it’s 2,147,483,647 elements. But in any real world scenario you should never use that many elements, as that probably is an indication that you haven’t implemented your code very well.

I hope that helps to clear things up Leigh, let me know if you still have any questions 🙂

What’s happening here is that you are invoking the toString() method on an array. By default, the toString() method of an array just outputs the memory location of the actual variable, NOT the contents of the variable.

Normally to address this, you would just need to override the toString() method yourself, and put in whatever implementation you want (If you don’t know what that means, no worries, it will be explained in the Java Object tutorial coming up). However, there’s one problem, you can’t override the toString method of arrays, because it’s built into Java.

So here’s the solution, just use this helper class to output the contents of your array:

Arrays.toString(crossword)

I believe that should do the trick. I didn’t test it out myself, so please let me know if it doesn’t work 🙂

Hey, I have found your lessons very usefull, but I still think that I am not getting any further making anything. To be honest, I cant remember how you write the stuff I learn. Are my concerns false, and will I learn this in the future, or am I just scrued?

Hi Trevor,
Useful information, good site!!!
I am learning java(beginner).I have a question if you don’t mind.
I have a list of names and I want to sort it in alphabetical order.
Any ideas?How do you do it ?