One-Dimensional Arrays
I often post about arrays and core Java on Twitter. Follow me here Follow @alextheedom
Introduction
Arrays are used to store data which can be either a primitive type or an object type. They are declared with that type and initialised with a size. Each elements is assigned a default value which depends on the declared type.
Interesting Facts
Arrays can be constructed with a size between 0 to 2,147,483,647. Internally arrays use integers for their indexes and therefore are limited to the maximum value of integers, which is 2^31-1. This value is also given by Integer.MAX_VALUE.
The array passed to the main method will be an array of zero length, if no arguments are passed on the command line.
Arrays are objects and live on the heap.
Gotchas
The length of an array is determined by scores.length and not scores.length().
The array declaration cannot contain a size otherwise it will throw a compiler error.
An object array’s elements are initialised to null. The object is not constructed and the constructor is not called.
Array indexes are zero-based, the first element has an index of 0. The index of the last element in the array is the length of the array minus one: scores.length – 1.
Array Declaration
An array declaration consists of a type, which may be a primitive type or and object type such as int, String or Thread and an identifier. The identifier is used to refer to the array on the stack. Square brackets [] are used to denote that it is an array.
Legal Declarations
Here are examples of some legal declarations:
[sourcecode language=”java” toolbar=”false”]
int[] scores;
Strings [][] names[];
[/sourcecode]
Array Construction
When an array is constructed a new object is created on the heap. You must specify the number of elements in the array because the JVM needs to know how much space to allocate.
The default values of the array’s type are assigned at the time of construction.
Default Values
The array element’s default value depend on the array’s declared type. Here is a list of types and their default value.
- boolean -> false
- byte/short/int/long -> 0
- char -> \u0000
- float/double -> 0.0
- reference -> null
If an array of type Thread in instantiated the Thread constructor in not called, the default value will be null. There are no Thread objects in the array only one array object of type Thread.
Legal Constructions
Here are examples of some legal constructions:
[sourcecode language=”java” toolbar=”false”]
int[] testScores = new int[4];
Thread threads[] = new Thread[5];
[/sourcecode]
The Thread constructor in not called, the default value is null. There are no Thread objects only one array object of type Thread.
Array Initialisation
Initializing an array gives its elements a value other than the default value. Array elements are initialised by assigning a compatible value.
[sourcecode language=”java” toolbar=”false”]
testScore[1] = 5;
threads[3] = new Thread();
[/sourcecode]
Primitive Arrays
A primitive array’s elements can accept any value that can be promoted implicitly to the declared type. For example an int array can accept all of int, byte, char and short values while a double can accept any number type.
Object Arrays
An object array’s elements can accept any object of any subclass of the declared type.
Shortcut Declaration, Construction and Initialization
An array can be declared, constructed and initialised all at once.
[sourcecode language=”java” toolbar=”false”]
int[] dots = {3,5,6};
[/sourcecode]
The size of the array is determined by the number of comma-separated items.
Anonymous Arrays
Anonymous arrays are Arrays without an identifier. As it doesn’t have an identifier it can’t be reused. Often they are used as arguments to methods that except an array as an argument. These are called just-in-time arrays arguments.
Invoke the method add with and array of floats.
[sourcecode language=”java” toolbar=”false”]
add(new float{1.2,2.5,2.0,1.6});
[/sourcecode]
The method add is declare as follows:
[sourcecode language=”java” toolbar=”false”]
public float add(float[] numbers){}
[/sourcecode]
An array size cannot be specified: new int[3] {4,7,2}; this code will not compile.
Array Reference Assignment
This refers to the assignment of the array object’s reference and not its elements. Remember that an array is an object in its own right and is not an object of the type of its elements.
You can reassign an array to an Object reference and cast it back to the original array type even if the original array was a primitive type array. Incorrect casting throws a ClassCastException at runtime.
Primitive Arrays
Only arrays of the same primitive type can be reassigned. So for example you cannot assign a byte array to an int array even though byte is smaller than an int. This is because an int is not a byte. They are not on the same inheritance tree.
Primitive arrays cannot be assigned to Object arrays, but you can assign Integer arrays to Object arrays.
[sourcecode language=”java” toolbar=”false”]
Object[] o = new Object[5];
o = new int[5];
[/sourcecode]
This will results in a type mismatch error.
Object Array
An object array of one type can be assigned to another as long as it is an array of a subtype to an array of a parent type. It must pass the IS-A test.
The following example demonstrates the assignment of arrays of similar and different types.
[sourcecode language=”java” toolbar=”false”]
public class Animal {
public void eat() {
System.out.println(“I am eating”);
}
public void sleep() {
System.out.println(“I am sleeping”);
}
}
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
public class Cat extends Animal {
public void meow() {
System.out.println(“Meow”);
}
public void sleep() {
System.out.println(“I am a sleeping cat”);
}
}
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
public class Dog extends Animal {
public void woof() {
System.out.println(“Woof”);
}
}
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
Cat [] c = new Cat[3];
Dog [] d = new Dog[3];
Animal [] a = new Animal[3];
[/sourcecode]
It is possible to assign a = c as a Cat is an Animal however it is not possible to assign c = a as an Animal is not a Cat or c = d as a Dog is not a Cat. The last two will result in a compile-time error.
a = c; Here we are assigning the Cat array to the Animal array. This works because Cat can do at least the same as Animal. Cat IS-A Animal.
c = a; Here we are assigning the Animal array to the Cat array. This will not work as the Animal cannot do as much as the Cat. Animal IS-NOT-A Cat.
If you assign an array of Cat objects to an array of Animal objects the Cat objects will behave like Animal objects. They behave the same way as if you used an Animal reference to refer to a Cat object.
When you retrieve an element you must cast the elements to Cat objects to be able to access the Cat methods that don’t exist in the Animal object.
In the following snippet we see an example of this.
[sourcecode language=”java” toolbar=”false”]
Cat[] c = new Cat[3];
c[0] = new Cat();
c[1] = new Cat();
c[2] = new Cat();
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
a = c; // Assigning a Cat array to an Animal refer
a[1].eat(); // Invoking the eat() method from the Cat object
a[1].sleep(); // Invoking the sleep() method from the Cat object
((Cat)a[1]).meow(); // Invoking the meow() method from the Cat object
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
Cat [] aa = (Cat[])a; // You can cast an entire array
aa[0].meow(); // No need to cast each element
[/sourcecode]
Different ways to create and initialize an array
Here are some examples of different ways to creat and initialize arrays.
[sourcecode language=”java” toolbar=”false”]
String[] sA = new String[] {“aaa”};
String[] sA = new String[1]; sA[0] = “aaa”;
String[] sA = {new String(“aaa”)};
String[] sA = {“aaa”};
[/sourcecode]
There is a no difference between String[] args and String args[].
However these is a difference here between String[] sa1, sa2; and String sa4[], sa5;. Here sa1 and sa2 are both arrays of strings. However only sa4 is an array of strings, sa5 is just a string.
If you liked this article about one-dimensional arrays you might like my article about multi-dimensional arrays.
Leave a Reply