java-arrays-tutorial

Learn basics of arrays in Java with this quick guide. Java arrays tutorial – the basics.

Java arrays – basic knowledge

Arrays are constructs that allow to store more than one value of the same type. Every value is associated with a numeric index that represents value position in the array.

Let us say that you want to create an array storing 7 strings that represent popular German car brands. We could write the code like this:

String[] cars = new String[7];
cars[0] = "BMW";
cars[1] = "VW";
cars[2] = "Porsche";
cars[3] = "Trabant";
cars[4] = "Opel";
cars[5] = "Mercedes";
cars[6] = "Audi";

In the first line you can notice that two square brackets [ ] were applied after the type name (String). This is a special syntax denoting that we want to store an array in our cars variable. The creation of the array is done by the new String[7] code. It creates a new array object of type String with capacity of holding 7 items.

In the next lines we assign our car brands values to the array. The number inside square brackets denotes which index of the array we want to access. Notice that we started using indexes from number 0 instead of 1 – in arrays, the indexing begins from number 0.

You may be wondering what is this index thing. Imagine the array as a container containing several smaller boxes to store our values. In order to be able to access individual boxes we must have some reference to them. In Java (and in many other languages) those references are numeric values, always beginning from zero.

Java array example

The illustration above visually represents the array created earlier. As you can see, every String inside the array has associated with it index.

Once you understand this concept, let’s move forward and learn how arrays are constructed.

Constructing Java arrays

You have already learned one way of constructing Java arrays. It uses the new keyword followed by desired data type and square brackets with number denoting desired array size (capacity).

String[] cars = new String[7];
cars[0] = "BMW";
cars[1] = "VW";
cars[2] = "Porsche";
cars[3] = "Trabant";
cars[4] = "Opel";
cars[5] = "Mercedes";
cars[6] = "Audi";

The code above is not the only way to create an array. Since declaring (creating) and initializing (providing initial value) at once is a very common operation, Java developers created a construct that allows to build arrays in a much shorter way:

String[] cars = new String[] { "BMW", "VW", "Porsche", "Trabant", "Opel", "Mercedes", "Audi" };

It looks much better, isn’t it? Notice that array size in the square brackets is not provided, as Java calculates required array size itself basing on the provided list of values.

Java developers went even further to simplify arrays creation, allowing you to create arrays in ever simpler and shorter form:

String[] cars = { "BMW", "VW", "Porsche", "Trabant", "Opel", "Mercedes", "Audi" };

The new String[] part can be completely dropped as Java knows the type of array by looking at the variable to which you want to assign your array.

Super simple stuff. Let’s continue.

Accessing Java arrays

As you have mastered Java arrays creation, it would be great to learn how to access data stored inside of them.

Accessing by index

The most basic way to access data in Java array is to use index number enclosed in square brackets. You have already seen this syntax on the beginning of this article.

String[] cars = { "BMW", "VW", "Porsche", "Trabant", "Opel", "Mercedes", "Audi" };
String myCar = cars[3]; // "Trabant"
String yourCar = cars[2]; // "Porsche
System.out.println(cars[5]); // prints "Mercedes" on screen

For loop

Sometimes you may want to access all elements of array one by one. Instead of having to type indexes manually you can use a for loop:

for(int i=0; i<cars.length; i++) {
   System.out.println(cars[i]);
}

You can notice cars.length is the code. length is a special property of every array that stores its size. As our cars array contain 6 elements, the value of cars.length in the code above equals to 6.

Also notice that iteration begins of i = 0. Don’t forget that array indexes start counting from zero!

Enhanced for loop

Iterating over all elements of an array is very common operation. For this purpose exists a special construct called enhanced for loop (also know as for-each loop) that simplifies such iterations:

String[] cars = { "BMW", "VW", "Porsche"};
for(String car : cars) {
   System.out.println( car + " is a good car" );
}

The code above will output:

BMW is a good car
VW is a good car
Porsche is a good car

The structure of enhanced for loop above is presented on the diagram below.

Java arrays foreach enchanced for loop

As you see usage of enhanced for loops is extremely simple, even simpler than regular for loops. Be sure to remember this construct very well, because it is very common construct that you will find in many Java codes.

Learn more about Java