Defining and initialising arrays

  • double[] x = new double[]{1,2,3};
  • double[] y = new double[3]{1,2,3}; (cannot define the array’s dimension when an initialiser is provided)
  • char[] charArray = new char[2];
  • charArray = {‘1’ ,‘2’,‘3’}; (Array constants can only be used to initialise the array)
  • char[] charArray2 = {‘1’ ,‘2’ ,‘3’ };
  • char[] cahrArray3 = new char[]{ ‘1’, ‘2’, ‘3’};
Arrays general
  • You can create arrays of zero length. The array passed to the main method is an array of zero length if no arguments are passed on the command line.
  • The length of an array: intArr.length
    • NOT: intArr.length().
  • Arrays are objects and live on the heap.
Declaring an array
An array declaration consists of a type (int, String, Thread) and an identifier i.e. the name used to refer to the variable, and square brackets [].
The declaration cannot contain a size, it will throw a compiler error. This is illegal: int[5] scores;
Examples of legal declarations:
  • Strings [][] names[];
  • int[] scores;
The JVM allocates space when you instantiate the array object.
Constructing an array
  • When an array is constructed a new object is created on the heap.
  • You must specify the number of elements in the array, the JVM needs to know how much space to allocate.
  • The default values of the array’s type are assigned.
Some legal constructions:
  • int[] testScores = new int[4];
  • Thread threads[] = new Thread[5];
The Thread constructor in not called, the default value is null. There are no Thread objects only one array object of type Thread.
Constructing multidimensional arrays
A multidimensional array is an array that contains a number of other arrays of the same type. In the first bracket we specify the number of arrays in our array.
int [][] myArray = new int [3][];
This array can contain up to three int arrays. The three arrays are defined as follows:
myArray[0] = new int[2];
myArray[1] = new int[3];
myArray[2] = new int[2];
The contents of each array are allocated as follows:
myArray[0][0] = 6; // Store the number 6 in the first element in the first array.
myArray[0][1] = 1; // Store the number 1 in the second element in the first array.
myArray[1][0] = 3; // Store the number 3 in the first element in the second array.
myArray[2][0] = 2; // Store the number 2 in the first element in the third array.
The first square brackets refers to the array.
The second square brackets refers to the element in the array referred to by the first square brackets.
Initializing an array
Initializing an array gives its elements a value other than its default value.
Initializing multidimensional arrays
int[][] scores = new int[3][]
scores[0] = new int[4]; // An int array of 4 elements is allocated to the first element
scores[1] = new int[6]; // An int array of 6 elements is allocated to the second element
scores[2] = new int[1]; // An int array of 1 elements is allocated to the third element
Short cut declaration, construction and initialization
One-dimensional arrays
int[] dots = {3,5,6}; The size of the array is determined by the number of comma-separated items.
Two-dimensional arrays
int[][] scores = {{5,2,4,7}, {9,2}, {3,4}};
this is the same as:
int[][] scores = new int[3][];
scores[0][] = {5,2,4,7};
scores[1][] = {9,2};
scores[2][] = {3,4};
NOTE: A two dimensional array is created because we have int[][] scores. The contents inside {} creates and allocates arrays. In this case three.
Array initial values
  • The initial values of array are as follows:



Arrays of primitives

  • Its elements can accept any value that can be promoted implicitly to the declared type; for example:
    • An int array can accept: int, byte, char, short
    • A double can accept any number type.
Arrays of Objects
  • Its elements can accept any object of any subclass of the declared type.
Anonymous Arrays
  • int[] testScores;
  • testScores = new int[] {4,7,2};
  • an array size cannot be specified… new int[3] {4,7,2};
Just In time array argument
  • Foof f = new Foo f();
  • f.takesAnArray(new int[] {7,7,8,2,5});
  • an array size cannot be specified. See above.
Assignment of array reference
  • This refers to the assignment of the array object reference and not its elements.
  • Can reassign an array to an Object reference and cast back to the original array even if the original array was a primitive type array.
  • Incorrect casting throws a ClassCastException at runtime.
Arrays of primitives:
    • Only arrays of the same primitive type can be reassigned.
    • Cannot assign a byte array to an int array even though byte is smaller than an int.
    • It’s because an int is not a byte. They are not on the same inheritance tree.
Array of object references:
    • Can assign an array of a subtype to an array of a parent type.
    • Must pass the IS-A test.


            Cat [] c = new Cat[3];
            Dog [] d = new Dog[3];
            Animal [] a = new Animal[3];
            a = c;
            c = a; // Does not compile
            c = d; // Does not compile
a = c; Here we are assigning the Cat array to the Animal array. This works because Cats can do at least the same as Animals. 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.
    • You must cast the elements to Cat objects to be able to access the Cat methods that don’t exist in the Animal object.


Cat[] c = new Cat[3];
c[0] = new Cat();
c[1] = new Cat();
c[2] = new Cat();
a = c; // Assigning a Cat array to an Animal refer
a[0].eat(); // Invoking the eat() method from the Cat object
a[0].sleep(); // Invoking the sleep() method from the Animal object
((Cat)a[0]).meow(); // There is no meow() method in the Animal object
Cat [] aa = (Cat[])a; // You can cast an entire array
aa[0].meow(); // No need to cast each element
Primitive arrays CANNOT be assigned to Object arrays.
  • Object[] o = new Object[5];
  • o = new int[5]; // results is a type mismatch.
But you can assign Integer arrays to Object arrays.
Different ways to create and initialize an array
String[] sA = new String[] { “aaa”};
String[] sA = new String[1] ; sA[0] = “aaa”;
String[] sA = {new String( “aaa”)};
String[] sA = { “aaa”};
Manipulating arrays
Coping an array we can use 
  • System.arraycopy(ArraySrc, StartPosSrc, ArrayDest, StartPosDest, Length). 
This will copy elements from ArraySrc to ArrayDest starting at position StartPosSrc in ArraySrc and copy to StartPosDest the number of elements equal to length.
There is a no difference between String[] args and String args[].
However these is a difference here:
  1. String[] sa1, sa2;
    1. Here sa1 and sa2 are both arrays of strings.
  1. String sa1[], sa2;
    1. Here only sa1 is an array of strings, sa2 is just a string.

Multidimensional arrays

  • These are both types of 2D arrays:
    • int [ ] [ ] i = new int [ 2 ] [ ]
      • i [ 0 ] [ 0 ] = 1;
      • i [ 0 ] [ 1 ] = 2;
      • i [ 1 ] [ 0 ] = 3;
      • i [ 1 ] [ 1 ] = 4;
    • is the same as:
    • int [ ] [ ] i = {{1,2},{3,4}}
  • The dimensions must be declared from left to right:
    • int[ ] a[ ] = new int[4][ ] ; and int[ ][ ] a = new int[5][4] ;
    • this is wrong: int a[ ][ ] = new int [ ][4] ;
  • The first element in the array is: i[0], this refers to the first array reference, the second element is: i[1], this refers to the second array reference.
  • Therefore it is possible to do the following assignments:
    • int [ ] y = i [ 0 ];
    • int [ ] x = i [ 1 ];
    • Note: its not necessary to put the extra [] because we only want to refer to the array reference not the contents of these arrays.

int i[][] = new int[4][4]; this means that there are two arrays and each can hold 5 elements. The first array is at i[0] and the second array is at i[1].

It looks like this:
0 [x]  [  ]
1 [  ]  [  ]
2 [  ]  [  ]
3 [  ]  [y]
4 [  ]  [  ]
To refer to x we would write: i[0][0] to refer to y: i[1][3]
The first number is the index of the array while the second number is the index of the element.
i[index of array][index of element]
Array constructors cannot have a generic type:



      ArrayList<String>[] ls = new ArrayList<String>[10];
      GenericAnimal<Cat> [] cats = new GenericAnimal<Cat>[10];


      ArrayList<String>[] ls = new ArrayList[10];
      GenericAnimal<Cat> [] cats = new GenericAnimal[10];