If you’ve ever done any programming, you’ve probably used variables. These are simple declarations that can hold a single unit of data. Name, for instance, is a variable that can hold any value – John, Paul, George or Ringo. But as useful as variables are, there are times when you’ll need to hold more than one value in a variable. In programming, we call these arrays. A band, for example, is an array that must hold at least 3 values (singer, guitarist and drummer, in most cases).

In this tutorial, I’ll teach you more about arraylists in Java and how to use them in your programs. For a more in-depth exploration of arrays, check out this course on Java fundamentals.

## So what exactly are arrays?

Let’s say we have a programmer, Jim, working in the IT department at a big company. One fine Friday evening, his boss walks into his office and says, “Jim, I need you to create a program to handle a boatload of numbers, find the total count of those numbers, and figure out their average, stat! And by stat I mean by this evening. Oh, and say hi to the wife and kids for me.”

If Jim doesn’t know about arrays, he better cancel the plans to bring his kids to Chuck E. Cheese’s that night because he’s in for a lot of coding.

But because Jim is a master of arrays, he’ll get this done in no time.

An array is simply a collection of elements of the same type stored in a contiguous block of memory. In simpler terms, an array is a collection of data. It makes storing a large number of values simple and easy. You can also look at arrays as a collection of variables that are the same type. So say for instance, we declare an array variable such as numbers. The variables we can get out of that array are numbers[0], numbers[2], numbers[44], etc. So you see in the case of Jim, he could have just used an array to finish that program in no more than 20 lines instead of more than 1000.

Now that we’ve defined arrays let’s get down to the nitty-gritty of it all.

## Creating Arrays

The first step of creating an array is to declare a reference for the array, and we do this by using square brackets, like so:

`int [] numbers;`

It can also be written as:

`int numbers [];`

Don’t worry too much about the second one though, unless you’re a C programmer.

The next step is to instantiate the array using the new keyword:

`numbers = new int[];`

What the statement above does is that it creates an array using new int[], then it assigns reference of the newly created array, which is numbers. The next thing in forming a proper variable in Java is to declare the variable reference:

`int [] numbers = new int [];`

Now the last thing to do is to determine the size of the array (an integer), and place it in the array brackets. So, here’s the final form:

`int [] numbers = new int [arraySize];`

Something to keep in mind when you’re determining the size of an array is that the elements of an array begin at zero, not one! Another interesting factoid about how arrays work, is that when an array is created, its elements are assigned the default values of 0 for primitive data types, ‘\u0000’ for char types, and false for Boolean types.

## Accessing an Array

Remember when we defined arrays as variables that hold a collection of smaller variables? If you look at those smaller variables, you’ll realize that they have a certain syntax. The elements in an array are accessed by using a reference to the variable and an index.

Let’s look at numbers again. To access the first element of this array, we use numbers[0], with ‘numbers’ being the reference and ‘0’ in the brackets being the index. When we do this, we can manipulate it in whatever way we like.

Let’s assign some numbers to the first four elements:

```int [] numbers = new int[10];numbers[0] = 1;

numbers[1] = 2;

numbers[2] = 3;

numbers[3] = 4;```

## Array Length

Remember when Jim’s boss told him that his program needs to know the number of numbers it’s crunching? Well, Java provides a very easy way of doing this. We can use the length attribute to determine how many elements are in the array. So here’s the syntax for using the length attribute:

`numbers.length`

You will see how useful this attribute is later on. You can learn more about it in this introduction to Java programming for beginners course.

## Array Initializers

Even though Java makes work so easy with arrays, you can make it even easier by using array initializers. These magical things create arrays without using the new keyword, allowing you to declare an array reference, instantiate an array, and fill the array with elements all in a single statement. These are great when working with small array with predetermined data. Look on the below code to see it for yourself:

`int [] primeNumbers = {1, 2, 3, 5, 7}`

So much easier to manipulate, right? Here you don’t even have to put the array size.

Ok, let’s do over that code we did earlier with the numbers array.

`int [] numbers = {1, 2, 3, 4};`

Amazing, isn’t it? What we did with 3-5 lines of code, we could actually do in one.

## Manipulating Array Elements

Earlier we started playing around with array elements. It was easy, but we still used too much code. An easier way of getting all those numbers in the array is by using a for loop. These are great when we have an idea of the conditions already, such as size of the array. So let’s see how we could use a ‘for’ loop to do what we did earlier:

```int [] numbers = new int[5];

for (int i = 0; i < numbers.length; i++){

numbers[i] = numbers[i] + i;

}```

As you can see, our new code is much smaller and will remain that way even when we add more elements to the array.

There is another way we could write for loops, and that is with the enhanced loop or ‘foreach’ loop. This allows us to bypass using index variables. The syntax for a ‘foreach’ loop is:

```for (elementType element: arrayName){

//do this

}```

This is basically saying, for each element in the array, pursue action in curly braces. This method cannot be used in all cases however.

Ready for something more complex? Learn how you can use Scala to scale up your Java applications!

## Copying Arrays

Arrays are fixed in size so sometimes you’d want to create a larger array and copy the contents of the smaller array into the larger one. There are three ways to do this:

• Use a loop to copy elements one by one

• Use the arraycopy() method in the System class

• Use the clone method

For now, we’ll only discuss the arraycopy() method. This method has the following signature:

`public static void arraycopy(Object source, int sourcePos, Object destination, int destinationPos, int length)`

sourcePos tells you where in the source array to copy from, and destinationPos indicates the location in the destination array to copy to. The length parameter tells you how many elements are to be copied.

## Let’s Help Jim!

With the knowledge that we have, let’s help Jim get home to his family. Let’s pretend for now that 10 numbers is a “boatload”.

That’s it! We’ve successfully used an arraylist to create a program and get our programmer friend home on time.

Page Last Updated: October 2013

### Top courses in Java

Java for Beginners
Navin Reddy
4.5 (1,860)
Java Interview Help
Bharath Thippireddy
4.4 (1,637)
Complete Java SE 8 Developer Bootcamp - OCA Prep Included
Intertech Training, Jeff Jensen
4.6 (9,697)
Modern Java - Learn Java 8 Features By coding it
Pragmatic Code School
4.5 (11,371)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.5 (4,092)
Bestseller
Learn Selenium with Java, Cucumber & Frameworks
Pavan Kumar
4.6 (8,451)
Bestseller