Welcome guest! Click here to register or login.
logo

<< Tutorial 7
Tutorial 9 >>

Arrays

***Please register FREE to rate this tutorial***


Topics
What is an array?
Syntax
Length method
Using arrays
Arrays as parameters
Object arrays
Examples
Example 1
Example 2
Example 3

What is an array?

In Java, an array is treated as an object. It requires the keyword new to create the array of a certain type. An array is also an ordered list of values. Here is how to define an array:

type name[] = new type[ size ];

where type is the data type of the array (int, char, String etc...); name is useful name for the array; and size is the number of elements in the array.

Here are just some declarations of arrays:

int heights[] = new int[5];

float f[] = new float[15];

char alphabet[] = new char[26];

boolean bools[] = new boolean[45];

String str[] = new String[10];

Notice that an array can be declared as a primitive array or an array of objects (with String above). Notice also that each of the above follow the same format.

Array syntax

There are some shorthand ways of declaring and intializing arrays. Let's see how to do some declaration:

As mentioned in an earlier tutorial, these two declarations are the same:

int arr[];

int[] arr;

Let's say you have more than one array that you want to decalre:

int[] a, b, c;

int a[], b[], c[];

These are the same declarations.

Now let's see how we can eliminate the new operator from some arrays. We can do what is called an initializer list. Let's see some exmaples:

int[] a = {1,2,3,4,5,6,7};

String str[] = {"Alex", "Chris", "John"};

boolean[] boo = {true,true,false,false,true};

Notice in each case above, there is no new keyword and the size of the array is not declared. Java will figure it out when the program is run.

Length method

A method that is built into arrays is called the length() method. This will return an integer representing the physical size of the array (that DOES NOT MEAN SIZE-1). Let's say we have this declaration:

int[] a = {3,4,5,9,10};

and we call the length method when dealing with a for loop:

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

What will be returned from the method will be 5, since the actual size of the array is 5.

Using arrays

All array elements are called an index (or subscript). All indicies begin at zero and finish at the size-1. So lets say that we have an array of size 5. The indicies go from 0 to 4 (since size-1 = 5-1 or 4).

All elements are accessed by using the square brackets. As an example, look at these code snippets:

heights[2] = 36;

str[5] = "Hello";

bools[21] = true;

etc...

Each of the above is assigning a value to a certain subscript of the array.

Here is a more formal example that will use an array of integers and print them to the console:

Example 1:
Simple array example

Download source code here (Right click - Save Tagret As...)

public class SimpleArray{

        public static void main(String[] args){
                int a[] = new int[5];

                //initialize the array:
                for(int i = 0; i < 5; i++)
                        a[i] = i*5;

                //print the array forwards:
                for(int j = 0; j < 5; j++)
                        System.out.print(a[j] + " ");

                System.out.println("");

                //print the array backwards:
                for(int k = 4; k >= 0; k--)
                        System.out.print(a[k] + " ");

                System.out.println("");
        }
}

The above program will simply assign the values (with the first for loop) 0 5 10 15 & 20 to the integer array a[]. It will then, with the other for loops, print the array forwards and backwards.

Notice that each for loop goes less than the actual size sticking to the rule of size-1.

Here is the output:

0 5 10 15 20
20 15 10 5 0

Arrays as parameters

In java, we know that objects are passed by reference when dealing with methods. The same applies for arrays since all arrays are objects. This time, if you change something in the array in the method, it WILL change the original value.

Here is an exmaple showing this concept:

Example 2:
Simple array method

Download source code here (Right click - Save Tagret As...)

public class SimpleArrayMethod{

        public static void main(String[] args){
                int a[] = new int[5];

                //initialize the array:
                for(int i = 0; i < 5; i++)
                        a[i] = i*5;

                change(a);

                for(int i = 0; i < 5; i++)
                        System.out.print(a[i] + " ");

                System.out.println("");
        }

        public static void change(int[] arr){
                arr[0] = 99999;
                arr[1] = 66666;
        }
}

When the method called change() is called, we change the values of a[0] and a[1] in both the method and the main(). For the purpose of this, it does not matter what the name of the formal parameter is as it will be referenced to the original array.

Here is the output:

99999 66666 10 15 20

Object arrays

An array can be declared as an object array. The most simple example is the String object:

String str[] = new String[5];

The above is an array of String objects of size 5.

It is important to note that the above just DECLARES the array and does not CREATE any String objects yet. It is up to you to do so later on in the program.

Here is small program to show both a declaration and creation of Strings:

Example 3:
Simple String array

Download source code here (Right click - Save Tagret As...)

public class SimpleStrings{

        public static void main(String[] args){
                String str[] = new String[5];

                for(int i = 0; i < str.length; i++)
                        str[i] = new String("Hello " + i);

                //preform a small change:
                str[0] = str[3];

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

}

The first for loop will actually create the String object (hence the keyword new and the constructor call). Each string will be "Hello i" where i is the loop counter.

After a small change in array (done by assigning the value of index 3 to index 0, the array is printed out. Here is the output:

Hello 3
Hello 1
Hello 2
Hello 3
Hello 4

<< Tutorial 7
Tutorial 9 >>