JBay Solutions Development Blog on Java, Android, Play2 and others
RSS RSS RSS RSS

Java Tutorial 6 - Arrays

  1. Introduction
  2. Arrays
  3. Lets talk Arrays
  4. Accessing values of an Array
  5. Setting values of elements
  6. Initing with values
  7. What is the size of this array?
  8. Accessing using invalid index
  9. References

Introduction

At this point we have all the knowledge we need to create Classes, methods, variables, instances of Objects, call methods, etc. These are the basic building blocks of any program made in Java.

In the last tutorial we finished with the following phrase:

Wouldn't it be nice to be able to have a list of Person objects stored in someway, instead of having to programmatically define a variable for each of the objects we create?

Well, lets look at Arrays then!



Arrays

For this Tutorial we will create another project with IntelliJ called "BeginnerJava6" , or just another empty folder named "BeginnerJava6" where we'll store our code. Create a package called "tutorial6", and we'll write all our code inside this package.

Lets create a class caller Starter with a main method:

package tutorial6;

public class Starter {
    public static void main(String[] args) {

    }
}

All very simple until now.

Lets talk Arrays

We'll kick it off with an example of an Array:

int[] listOfInts = new int[10];

What is an Array? In Java, the simplest way of describing an array is: a structure that stores values. These structure have a few properties that are very important to understand :

  • They are of fixed size

So, an array has a fixed size that is defined when the array is created. In our example of listOfInts, it is a structure that can take 10 elements : new int[10]

  • It is typed

Which means that they store elements of a specific type. This specific type is defined also when the array is created. In our example it stores int values.

  • It is ordered

This means that the elements have a specific position on the array, and that adding or removing elements, does not change the position or the remaining elements in the array.

These are a few examples of other types of arrays:

  • float[] listOfFloats = new float[10]; - An array of floats of size 10
  • double[] listOfDoubles = new double[50]; - An array of doubles of size 50
  • String[] listOfStrings = new String[9000]; - An array of Strings of size 9000

As you can see, the notation is quite simple! First the programmer defines the type of array it wants to work with, and a name for that array:

  • int[] listOfInts : This is the declaration part of the statement on our first example

Then the programmer instantiates the array, using the new keyword, like it was an object, but instead of using the ( ) to pass arguments to a constructor, the programmer uses [ ] with the size of the array he need to create :

  • new int[10] : This is the instantiation part of the statement, where the size of the array is specified



Lets create an array of ints inside the main method of the Starter class:

package tutorial6;

public class Starter {

    public static void main(String[] args) {

        int[] listOfInts = new int[10];

    }

}

A few things to take notice, and recapping from the last tutorials :

  • the listOfInts variable is of Method Level Scope
  • because it is of Method Level Scope , it only exist inside that method
  • and because it is of Method Level Scope it does not have an Access Modifier
  • inside the main method we create the array variable and instantiate it with a size of 10
  • it does nothing else

Everything is making sense, yes?

Very easy, give it a compile and run it. If it does absolutely nothing, that means that it is good.

Accessing values of an Array

To access the values inside the array we do : arrayName[ POSITION ] where POSITION is the index of the array we want to access.

The index of an array is an int always starts at 0 and ends at size-1 of the size defined at its instantiation.

Lets modify the main method of the Starter class to print all the elements of the array we are creating:

public static void main(String[] args) {

    int[] listOfInts = new int[10];

    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

}

Compile and run it. The result should be something like this:

Value at index 0 : 0
Value at index 1 : 0
Value at index 2 : 0
Value at index 3 : 0
Value at index 4 : 0
Value at index 5 : 0
Value at index 6 : 0
Value at index 7 : 0
Value at index 8 : 0
Value at index 9 : 0

Notice that all elements of the array are filled with 0s, this is an important detail to know about arrays, they are initialized with with default values of the type of array they are, hence:

  • int[] ints = new int[10] : all elements will be 0
  • double[] doubles = new doubles[10] : all elements will be 0.0

If the array was an array of objects, then the default value of each element would be null, which is to mean that the position is empty and has no object. We'll see more about what null means when looking at Reference Variables. Some examples :

  • User[] users = new Users[10] : all elements will be null
  • String[] strings = new String[10] : all elements will be null

Give it a try and see the results yourself.

Now we can read the elements in the array positions, but what about setting those values?



Setting values of elements

To set the value of a particular element of an array we use the same notation as before: arrayName[ POSITION ] where POSITION is the index of the array we want to access, and then we assign the value using the = operator, like so:

listOfInts[5] = 1000;

This last statement will assign the value of 1000 to the element on the 6st position! Yes, 6st position, remember that the index starts at 0, and 0 is the first position of the array.

As an exercise, modify the main method to first assign values to all elements of the array and then print them out.

The end result should be something like this:

public static void main(String[] args) {

    int[] listOfInts = new int[10];

    listOfInts[0] = 199;
    listOfInts[1] = 9349;
    listOfInts[2] = 9229;
    listOfInts[3] = 11243;
    listOfInts[4] = 952;
    listOfInts[5] = 13;
    listOfInts[6] = 422;
    listOfInts[7] = 4239;
    listOfInts[8] = 527;
    listOfInts[9] = 874;


    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

}

And running this last example will produce:

Value at index 0 : 199
Value at index 1 : 9349
Value at index 2 : 9229
Value at index 3 : 11243
Value at index 4 : 952
Value at index 5 : 13
Value at index 6 : 422
Value at index 7 : 4239
Value at index 8 : 527
Value at index 9 : 874

There is another way to set the values of an array, which is to assign the values when initializing the array.



Initing with values

In some cases, when we create an array we already know what values we want to place in it, and in those cases it makes a lot more sense to just set those values during instantiation, instead of instantiating an array with a specific size and then writing some more code to insert the values in their correct positions.

This is done in the following way:

int[] listOfInts = new int[]{ 111,222,333,444,555,666,777,888,999,1000 };

This small example will create an array of ints called listOfInts, with a size of 10although it is not specified directly, and with the following ints 111,222,333,444,555,666,777,888,999,1000 in their ordered position.

Notice that by using this notation :

  • The size of the array is specified indirectly , it is the size of parameters provided.
  • The order of the values will be the corresponding index, starting with 0

As an exercise, modify the main method to assign values during instantiation of the array, and print those values out.

The end main method should look something like this:

public static void main(String[] args) {

    int[] listOfInts = new int[]{ 111,222,333,444,555,666,777,888,999,1000 };

    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

}

Executing this last main method will produce:

Value at index 0 : 111
Value at index 1 : 222
Value at index 2 : 333
Value at index 3 : 444
Value at index 4 : 555
Value at index 5 : 666
Value at index 6 : 777
Value at index 7 : 888
Value at index 8 : 999
Value at index 9 : 1000

What is the size of this array?

Another really important detail of working with arrays, is getting the size of an array. In our examples thus far we created the arrays, we know the sizes, we know what they contain, but this might not always be the case.

To get the size of an array we access the length public int variable that exists on all arrays, because arrays are objects (remember, if a variable is not of a primitive type, it is an object) :

listOfInts.length;

As an exercise, modify the main method we have been working with, and after printing all the values print also the size of the array.

The end result could look like this:

public static void main(String[] args) {

    int[] listOfInts = new int[]{ 111,222,333,444,555,666,777,888,999,1000 };

    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

    int size = listOfInts.length;
    System.out.println("Size of array is : " + size);

}

Notice that in this bit of code, this particular section :

int size = listOfInts.length;
System.out.println("Size of array is : " + size);

Could be rewritten as:

System.out.println("Size of array is : " + listOfInts.length);

Which would avoid creating another variable and assigning a value to that variable.

If you have been trying these exercises, and writing code as you are learning it, you probably already tried to access an element of an array using an index that is larger than the size of the array itself. If you did, then you got an error. Lets look at that now.



Accessing using invalid index

Like it was said in the beginning of this tutorial, an array has a fixed size, and it's index goes from 0 to size-1, so what happens when we use an index that is smaller than 0 or bigger than size-1?

Lets modify the main method to try it out:

public static void main(String[] args) {

    int[] listOfInts = new int[10];
    System.out.println("Value at index 0 : " + listOfInts[-1] );

}

Compiling this code will produce no errors.

Running the compiled code will generate an exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at tutorial6.Starter.main(Starter.java:7)

The same is true for trying to set a value with an invalid index:

int[] listOfInts = new int[10];
listOfInts[20] = 1000;

This will also produce an exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at tutorial6.Starter.main(Starter.java:7)

One way to avoid these exceptions, of type ArrayIndexOutOfBoundsException, if to verify before if the index we are about to use is smaller or equal to the size of the array, and also larger than 0. We'll see how to do that on the next tutorial.

If you feel ready, the next Tutorial : Tutorial 6 - Flow Control

References



comments powered by Disqus