≡ Menu

Java Arrays

We’ve talked about the concept of Java Arrays back in “Five basic concepts of any programming language #3 – Data Structures”, so if you like to you brush up on what we talked about, feel free.

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...

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

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 = 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

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:

String[] contacts;
contacts = new String[10];

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:

String[] contacts = new String[10];
for (int i=0; i < contacts.length; i++)
  contacts[i] = "person" + i;

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:


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.



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

String[][] crossword = new String[4][4];
crossword[0][0] = "A"; crossword[0][1] = "D"; crossword[0][2] = "L"; crossword[0][3] = "E";
crossword[1][0] = "Q"; crossword[1][1] = "N"; crossword[1][2] = "N"; crossword[1][3] = "O";
crossword[2][0] = "W"; crossword[2][1] = "I"; crossword[2][2] = "N"; crossword[2][3] = "D";
crossword[3][0] = "V"; crossword[3][1] = "K"; crossword[3][2] = "N"; crossword[3][3] = "E";

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.


{ 21 comments… add one }

  • Tejus August 9, 2012, 9:26 am

    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?

    • Durim February 8, 2013, 2:51 am

      Hello Tejus!

      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!

      Trevor, please correct me, if I’m wrong:$

      Thank you!

      • Trevor Page February 8, 2013, 7:35 am

        You got it Durim, that’s absolutely correct.

        Thanks for answering that question, it was asked back in August and I completely missed it.

        My apologies to Tejus for not answering, thankfully the community here rocks 🙂

        • Durim February 8, 2013, 2:45 pm

          Nothing Trevor;)
          It’s my pleasure to post in a web site like yours:)

          • Flavio Machado September 4, 2014, 1:45 pm

            Actually, in this case “length” is an instance variable, not a method (note that there are no parentheses after it).

  • Leigh August 14, 2012, 7:05 pm

    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?

    Knew I shouldn’t have waited six days before I came back to this.

    Thanks again.

    • Trevor Page August 14, 2012, 8:24 pm

      Hi Leigh,

      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 🙂


  • raymond December 2, 2012, 10:17 pm
    public class Trial {
    	public static void main(String[] args){
            String[][]crossword= new String[4][4];
    	crossword[0][0] = "A";	crossword[0][1] = "B";	 crossword[0][2] = "C";  crossword[0][3] = "D";
    	crossword[1][0] = "E"; 	crossword[1][1] = "F";	 crossword[1][2] = "G";  crossword[1][3] = "H";
    	crossword[2][0] = "I";  crossword[2][1] = "J";	 crossword[2][2] = "K";  crossword[2][3] = "L";
    	crossword[3][0] = "M";	crossword[3][1] = "N";  crossword[3][2] = "O";  crossword[3][3] = "P";

    -whats that?? it wont compile as..

    A B C D
    E F G H
    I J K L
    M N O P

    • Trevor Page December 3, 2012, 10:44 am

      Fantastic question Raymond, thanks for asking it.

      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:


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

  • Khalid February 4, 2013, 4:35 am

    A B C D
    E F G H
    I J K L
    M N O P
    I’m so interested in programming Java while seeing your post.
    How can I get this kind of result?

    Thanks for your great time!

    • Trevor Page February 5, 2013, 12:03 pm

      One way would be to use the Arrays.deepToString() method:

      String[][] crossword = new String[4][4];
      crossword[0][0] = "A"; crossword[0][1] = "B"; crossword[0][2] = "C"; crossword[0][3] = "D";
      crossword[1][0] = "E"; crossword[1][1] = "F"; crossword[1][2] = "G"; crossword[1][3] = "H";
      crossword[2][0] = "I"; crossword[2][1] = "J"; crossword[2][2] = "K"; crossword[2][3] = "L";
      crossword[3][0] = "M"; crossword[3][1] = "N"; crossword[3][2] = "O"; crossword[3][3] = "P";
  • 1eye May 9, 2013, 12:56 am

    Can a array have unlimited bllocks of storage, if the array starts at 0 ,example 0 – 255 ; or can it only store 10 0-8

    • Trevor Page May 9, 2013, 8:09 am

      Arrays cannot have unlimited storage, as you must define the length of the Array when you instantiate it.

      So for example:

      String[] largeStringArray = new String[5000];

      This code would define an array with 5000 blocks of storage (0 – 4999)

  • Renze Stolte June 18, 2013, 2:01 pm

    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?

  • michael July 30, 2013, 7:00 pm

    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 ?


  • francis July 1, 2015, 3:29 pm

    whats the use of ‘i’ and ‘i++’ in the code.. im a new one to coding so pleasee explain in an understandable language

    • Trevor Page July 9, 2015, 9:26 am

      ‘i’ is just a variable name, it’s most often used to represent a “counter” of some sort… so a variable that will count from, say, 0 to 10 for example.

      The ‘i++’ code is actually just a sort of “short cut” way of writing this: ‘i = i + 1’. When you write ‘i = i + 1’, all you’re doing is incrementing the value in the ‘i’ variable by one.

      So ‘i = i + 1’ and ‘i++’ do the exact same thing. It’s just quicker to write ‘i++’ for us lazy coders 🙂

  • Shruti February 21, 2017, 7:24 pm

    Hey !
    I tried out this code in my editor and I got the square brackets displayed as well.
    How can I get rid of them?

  • lollapalooza2017tickets.com May 1, 2017, 11:41 am

    In the weeks and even months major up to the extremely anticipated Lollapalooza
    lineup announcement, a wealth of rumors generally circulate
    concerning prospective headliners and supporting acts.

  • Anurag Singh May 16, 2017, 3:27 am

    hello sir
    this is really nice article about array and this article is very useful for everyone who want to learn java or java array.
    please keep posting for us.
    thank you

Leave a Comment