Software Development Basics – Arrays

This Post is part of the Variables & Operators block. I am going to introduce to you the wonderful Arrays.

Arrays

An array is simply a container of multiple values of the same type. Along with the specific data type it also has a specific length or capacity.

You can use it, for example, to store 10 integer numbers on it. If you try to add a different data type, say a double, you will get an error. And also if you try to add 11 numbers, you get an error.

So… an array is a container with fixed lenght or capacity that can only contain one specific data type.

You can have access to each element in the array. For this you need to access it via its index. The index is the position the element has in the array.

BIG RED WARNING HERE: the index of the first element in an array is ZERO.

This makes the last index of the array to be the array’s length – 1.

If you have an array with 10 elements, the first element will be at index 0, the last element will be at index 9. REMEMBER IT STARTS AT ZERO!

Arrays

Arrays

Array Declaration and Initialization

As with any variable, you need to declare an array. The next line shows how to declare an array of ints, one of booleans and one of doubles.


// Array declaration.
int[] arrayOfInts;
boolean[] arrayOfBooleans;
double[] arrayOfDoubles;

In its general form you declare arrays like this:


dataType[] arrayName;

where dataType can be anything you want: int, double, float, etc, even your own objects (more on objects in later post).

Ok, you declared your array. Now you need to create it. There are two ways of doing this.
The first way is to create a new array of the data type that you want and set its lenght, like shown below.


// Initalizing the int array.
// You will need to indicate the lenght of your array here.
// Your array will have a 0 for value in all its positions.
arrayOfInts = new int[10];

 

The second way is to add the values to your array when you declare it, as shown below. In this form, the length of your array will be determined by the number of elements you add to it. In this example, arrayOfBooleans will have a length of 8.


// Initializing the boolean array.
// You can set the values when you create the array.
// Your array will get its length from the number
// of values that you add here.
boolean[] arrayOfBooleans = {false, false, true, true, false, true, true, false};

Adding Values to the Array

If you use the second way to initialize the array, you already have some values in it. But if you use the first way, you need to add values to your array.

For doing this, you simply tell the array the position where you want to add the value and assign the value to it.


// Adding values to the int array.
arrayOfInts[0] = 0;
arrayOfInts[1] = 54;
arrayOfInts[2] = 8;
arrayOfInts[3] = 90;
arrayOfInts[4] = 1;
…

You can also use cycles to add values to your arrays. The important thing here is to know how to assign values to it.


arrayName[positionToAddValue] = valeOfTheTypeOfTheArray;

 

Array data manipulation

You can get any value from your array just by indicating the position you want to get the value from.


System.out.println("ArrayOfInts at position 5: " + arrayOfInts[5]);

But most of the times you will want to iterate through all your array to do something with your data. You can use the for loop to iterate through your array.

If you remember, the for loop needs a condition to know until when to iterate. This time you need to iterate through all your array. This means that you will iterate until your for counter is less than the array length (REMEMBER that the last position or index in your array is the array length – 1, so this will work because the condition is less than the length. If you use less than or equal to the length it will cause an error).


// Adding values to the double array.
// You use the array length as the condition.
// Remember that the last position or index in your array
// is the array lenght - 1.
// You could also have i <= arrayOfDoubles.length - 1.
for(int i = 0; i < arrayOfDoubles.length; i++){
    arrayOfDoubles[i] = (double)i;
}

You could also use the alternate for version as shown below.
// Printing the array of doubles.
for(double d : arrayOfDoubles){
    System.out.print(d + " ");
}

Important Note Regarding the Array’s Length

When you create your array you specify its length. Once you do this, you cannot change its length. It is very important that you remember this.

Multidimensional arrays

You can declare an array to be multidimensional. The most used multidimensional arrays are the 2D arrays. You can visualize this 2D array as a matrix, having rows and columns. We won’t cover arrays with more than 2 dimensions here.

When you want to declare a multidimensional array, you need to add another pair of square brackets []. Each pair represents a dimension. You need to set the length of each dimension.


// Declaring a multidimensional array of Strings.
// This array will have 2 dimensions, each with a length of 3.
String[][] multidimensionalArrayOfStrings = new String[3][3];

You can initialize the array the same way as before, but now if you want to add values in the initialization, you need to separate by curly brackets and commas, each dimension.


String[][] multidimensionalArrayOfStrings = {{"dim1-value1","dim1-value2","dim1-value3"},
                                             {"dim2-value2","dim2-value2","dim2-value3"}};

You can access the elements in the array the same way as before, but now you need to tell the position on both dimensions.


System.out.println("Value of 2D array in 1,2: " + multidimensionalArrayOfStrings[1][2]);

Also you can iterate through all the elements. You will need two for loops: one to iterate through each row, and while you are in the row, another for to iterate through all columns of that row.


// First for loop iterates through all the rows. In this example, the array's length
// is the number of rows - the lenght of this dimension.
for(int row = 0; row < multidimensionalArrayOfStrings.length; row++){
    // Second for loop iterates through all the columns of each row.
    // You can get the number of columns using the array's first row.length.
    for(int column = 0; column < multidimensionalArrayOfStrings[0].length; column++){
        System.out.print(multidimensionalArrayOfStrings[row][column] + " ");
    }
    System.out.println();
}

You can also use the alternate for form.


// This first for will get the array of columns for each row.
for(String[] columns : multidimensionalArrayOfStrings){
    // This second for will get the value of each column.
    for(String column : columns){
        System.out.print(column + " ");
    }
    System.out.println();
}

 

You can find all the source code in Github.

—-

Arrays could become tricky to handle and to create. There are other data structures you can use to better handle your data, but arrays are the most basic and you need to know about them and master them.

Try to play with arrays, declare them, initialize them and iterate on them. After some confusing errors I’m sure you will master them. If you have questions leave a comment or email me.

See you next week

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s