Skip to main content

Student Portal > Contests > 

Programming Contest Central

   
Welcome students Resources Competition ProfilesFAQ
  Contest calendar
  Problem of the month
  Past problems
  Games and brainteasers
  Successes
  Tutorials

Arrays (One-Dimensional)
What is an array?
Declaring and Initializing Arrays
Array Sizes
Passing Arrays
Creating an Array of Objects
Garbage Collection
Cloning Arrays
Related Links


What is an array?

An array is a collection of variables of the same type (primitive or reference types) that are stored in consecutive memory locations (in RAM) and referenced by a common name. Arrays are multi-dimensional. There are single dimension arrays, 2-D arrays, and even 3-D and 4-D arrays. However, unlike real objects, you cannot imagine arrays with more than three dimensions (but they do exist!).


Declaring and Initializing Arrays

Declaring an array means creating a REFERENCE to that array (stored in memory). However, the array itself is not created yet. You must also initialize the array. Initializing an array means to create an instance of an array. In other words, you have created an object that is of an array type. There are two ways to initialize arrays. See the following examples.

Example

int [] numbers=new int[10];
//the declaration part comes before the equal sign
//the first word int indicates the type of array it is (in this case, an array with int elements)
//the "[]" indicates that it is only a one dimensional array
//the next word indicates the name numbers is used to reference the array
//the initialization part comes after the equal sign
//new int[10] means that a 1-D array of 10 int elements is created (Note the keyword new)

Here is a visual interpretation of the array:



Notice that the numbering of elements starts from 0 and ends at 9. All arrays in Java start with the zero index! Also, the default value of every element is 0 because it is an integer and you have not set the values of each element yet.

//another way to directly create an array is the following:
numbers = {1,2,3,4,5,6,7,8,9,10};
//this would give the following:



After the array is created, you can access and change any element with:

     arrayName [indexNumber]=value;


Example

numbers [6]=100;
//Now the array would look like:



Note: the index number specified was 6, so the element with the index number 6 is called upon, and the value was changed to 100.


System.out.println(numbers[0]);


System Output

1

However, if you try to access an element that is not declared or out of range, you will get an error:

System.out.println(numbers[11]);
//returns an error

System Output
java.lang.ArrayIndexOutOfBoundsException: 5


Array Sizes

There are two types of sizes when referring to arrays. One is the physical size, which means how many elements exist in an array. The second size is the logical size, which means how many elements are actually USED in an array. The logical size must be smaller or equal to the physical size.

One thing to be careful about when creating array sizes is that you do not want to create an array with a physical size smaller than the logical size (the array will run out of space the the program will crash) and you do not want to create an array with a physical size a lot greater than the logical size either (because that would waste a lot of memory). The physical and logical sizes should be roughly the same, therefore you must use your own judgment to decide on the physical size when creating arrays.

To determine the size of an array, you can use the .length property. This property will return an integer of the number of elements in an array.

Example (using the same example above)
System.out.println(numbers.length);

System Output
10

Example 2

The following is a similar example to the previous example, but this time a String array is used.

String[] names=new String[5];

Here is a visual interpretation of the array:



Note: the value null means that the value for that element has not been declared.

numbers [2]="hello";
//this would give the following:



System.out.println(names[5]);

System Output
java.lang.ArrayIndexOutOfBoundsException: 5


Passing Arrays

Just like primitive variables (int, char, boolean), arrays can be passed through parameters. However, because arrays are a reference variable, a local copy is NOT produced in the method called. Instead, when array parameters are passed, the REFERENCE to the array is passed to the called method. In other words, the parameter indicates to the method called the location of the array. Therefore any changes to this array will affect what the actual array in the calling method points to as well.

Example

public class arrayParameters
{
      public static void main (String[]args)
      {
      int []a= new
int[5]; //creating an array
      ..
      method1(a); //passing the array a as a parameter
     
      for (int i=0; i<a.length;i++)
            System.out.println(a[i]);
      }

      //method: changeFourth
      //purpose: to change the fourth element of an array to 5
      //parameters: the 1-dimensional array
      //return: the array
      public static int[] method1(int[] b)
      {
            b[3] = 5;
            return b; //returns the array b
      }
}

System Output
0
0
0
5
0


Creating an Array of Objects

To create an array of objects means that every element in an array is an object, or instance of another class. For example, if you wanted to make an array filled with Circle objects (see Object-Oriented Programming Tutorial for the Circle class), you would do it in the following way:

Circle [] c=new Circle[5];

The above statement has created an array called c, with 5 Circle elements. At the moment, each object is null. You have just created the following:



To create the 5 Circle objects, you must use the new function for each element as such:

for (int i=0;i<5;i++)
      c[i]=new Circle();





Garbage Collection

Garbage collection is a process used in Java to determine if there are any objects without a reference to them. This also applies to arrays. If found, those objects are declared garbage and the memory (in RAM) that was used for those objects now become available once again. Garbage collection occurs automatically. However, because it does not happen very frequently (since it is a low-priority task), you can force garbage collection to occur using the following:

System.gc();


Cloning Arrays

Study the following figure before reading ahead about cloning arrays.

Sample Object

Figure 2.


test is the name of the object that was created. size is a field with a value of 5, and element is the reference to an array of size 5 (pointing to outside the box.

When cloning (making a second copy) of reference types, such as arrays, the assignment operator will only create a copy to the reference, but it will not create a second copy of the object or array. All objects in Java are subclasses (refer to Inheritance and Composition Tutorial for more detail) of the Object class, and one of the predefined methods is the clone() method . To make a copy of another object, you must use the clone() method, but since this method returns an Object reference to the new reference, you must cast the returned reference back to the actual type of object. Follow the example below for an in-depth analysis of cloning arrays.

Example
public class CloningTest
{
      public static void main(String[] args)
      {
            int[] element = new int[5];
            for (int i = 0; i < 5; i++)
            {            
                  element[i] = i;
                  System.out.println(element[i]);
            }

            //the following line will clone the array as in Figure 1.
            //the following line has also cast the cloned object into an array.
            int[] newElement = (int[]) element.clone();
            for (int i = 0; i < 5; i++)
                  System.out.println(newElement[i]);
      }
}

Figure 1.


System Output
0
1
2
3
4
0
1
2
3
4

However, if you have an object with references to other objects, such as a NumbersClass object which has an array as one of its fields, the above clone() method alone will not create a true copy of the NumbersClass. This clone() method will only create a shallow copy of the object, meaning that a new object is created, but it will still point to the other references, and those objects will NOT be copied. In this case, the arrays will not be copied. In order to create a true copy (or a deep copy), meaning that even the other objects that NumbersClass points to are copied, you must override the clone() method by rewriting it yourself. Refer to the next example for an in-depth analysis of advanced cloning.

Example 2

//Title: cloning
//Purpose: to demonstate how to properly clone objects
//Output: none

public class cloning
{
      public static void main(String[] args) throws      
CloneNotSupportedException {
            NumbersClass test = new NumbersClass();
            //For the following line, on the left of Figure 2., badCopy points
            //to the same object as the test object, which is ineffective for
            //cloning purposes
            NumbersClass badCopy = test;
            //The following line is a call to the rewritten clone() method in the
            //NumbersClass (refer for Figure 3.)
            NumbersClass goodCopy = (NumbersClass) test.clone();
      }
}

 

Figure 2.



Figure 3.


/* Name: NumbersClass
* Purpose: to create a numbers class with an array of numbers
* Fields:
* size - the size of the array
* element - the array of numbers
* Methods:
* constructors - creates the object
* clone - to return a clone (deep copy) of the NumbersClass object
* toString - to return a String containing all the values
* of the elements in the element array*/
public
class NumbersClass implements Cloneable {
      protected int size;
      protected int[] element;

      //purpose: to initialize the size and create the element array
      //parameters: size of array
      //return: none
      public NumbersClass(int n)
      {      
            if (n >= 0)
                  size = n;
            else
                  size = 0;
            element = new int[size];
            for (int i = 0; i < size; i++)
                  element[i] = i + 1;
      }

      //purpose: creates an array with size 0
      //parameters: none
      //return: none
      public NumbersClass()
      {
            this(0);
      }

      //purpose: to return a clone (deep copy) of the NumbersClass object
      //parameters: none
      //return: the cloned class object
      public Object clone() throws CloneNotSupportedException
      {
            //the following line creates a shallow copy of the object using a
            //new object reference by calling super.clone()
            NumbersClass newObject = (NumbersClass) super.clone();
            //the following line manually clones each of the reference types the
            //original object was pointing to by calling the clone() method,
            //creating a deep copy of the object
            newObject.element = (int[]) element.clone();
            //the following line returns the cloned object
            return newObject;
      }

      //purpose: to return a String containing all the values
      //of the elements in the element array
      //parameters: none
      //return: string containing values of elements of the array
      public String toString() {
            String result = "";
            for (int i = 0; i < size; i++)
                  result = i + " ";
            return result;
      }
}

In the above program, the clone() method is rewritten manually, and therefore the line

       NumbersClass goodCopy = (NumbersClass) test.clone();

correctly clones the entire test object. However, if the clone was not manually rewritten, this is what the above line would give:

Figure 4.



 

This is incorrect because the two objects are still attached. Making a change to element in the goodCopy object will also change element in the test object, meaning that goodCopy is not an independent cloned object. Cloning objects and arrays is a tricky technique, so be sure to watch out for any objects having references pointing to other objects!



For more information on arrays, click on the links below:
Sun Java Tutorials Lesson on Java arrays.
Java Quick Reference A tutorial on arrays.






Back to top
 


Quick links

Student forum

Teacher resources

RSS Feed