Working with Java Arrays

Declaring, Constructing and Initializing Arrays

Arrays are objects in Java that store multiple variables of the same data type. Arrays can hold either primitive data types or object references, but the array itself will always be an object type. Multi-dimensional arrays are just arrays of arrays, the dimensions in a multidimensional array can have different lengths. An array of primitives can accept any value that can be promoted implicity to the declared type of the array (byte can go into a int array). An array of objects can hold any object that passes the IS-A (instanceof) test for the declared type.

Declaring an Array Arrays are declared by stating the type of element the array will hold, which can be a primitive or an object. The array will not be determined at this point and the compiler will throw an error if you do. You never include the size of the array.
Constructing an Array

Constructing an array means creating the array object on the heap - in other words, doing a new on the array type, at this point you determine the size of the array so that the space can be allocated on the heap.

Primitive arrays are given default values when created unless otherwise specified (see above for default values). Objects arrays are given null values as default unless otherwise specified.

Initializing an Array

Initializing an means putting things into it. if you have an array of objects, the array does not hold the object but holds a reference to the objects. The default value of an element of an array which has a type of object is null, so becareful if you try to use this element otherwise you get a nullpointerexception error.

To access an element within the array you start from 0, if you get an ArrayIndexOutOfBoundsException it means that you are trying to access an element that does not exist (not within range).

The position number in square brackets is more formally called a subscript (index), a subscript must be an integer or an integer expression. You cannot change the size of an array once constructed, however there are other list types that can be grown or shrunk see Collections for more details.

Array Examples
Declaring an Array examples
int[] array1;                  // Square brackets before variable name (recommended)
int key [];                    // Square brackets after variable name, legal but not recommended

Thread[] threads;              // Recommended
Thread threads [];             // Legal but less readable

String [][][] occupantName;    // 3 dimensional array
String [][] managerName;       // 2 dimensional array
int[5] array1;                 // ERROR: You cannot include the size of an array, the compiler will complain 

int a, b[], c;                 // you can declare multiple variables and arrays on the same line

String[]  string Array[];      // this actually declares a multi-dimension String array
Constructing an Array examples
int[] array1;                     // Declare the array of ints
array1 = new init[4];             // constructs an array of 4 elements and assigns the variable name array1
Note: the array will now be on the heap with each element set to 0 (default)

int[] myIntArray = null;          // you can set an array to null

Object o = new int[5];            // Array's are Objects so this is perfectly legal

int[] array1 = new int[14];       // Declare an array in one statement, 14 elements are created (0-13)

int[] a = new int[]{1,2,3,4,5};   // You can combine the initializer with the new operator, but don't define the size

int[] array1 = new int[];         // ERROR: This swill not compile missing array size

# Multidimension arrays
int[][] ratings = new int[3][];   // only first brackets are given a size which is acceptable 
Initializing an Array examples
// Setting values for sepcific elements within the array 
animals[0] = new Animal();              // Object type 
x[4] = 2;                               // primitive type

# Initializing a multidimensional array 
array[0] = new init[4];                 // Specify that element 0 holds an array of 4 int elements
array[1] = new init[6];                 // Specify that element 1 holds an array of 6 int elements
          
array[0][0] = 5;
array[0][1] = 6; 
Declaring, Constructing and Initializing on one line
int[] dots = {3,6,9,12};                                        // 4 element array of type int

int[][] scores = { {3,4,5}, {9,2}, {3,4,5} };                   // Multidimensional array 
 
String[] names = {new String("Paul"), new String("Lorraine")};  // Object array
String[] names = {"Paul", "Lorraine"};                          // Shorthand of above
Anonymous Array
// A second short cut is called an anonymous array, below creates a 3 element array of type int. 
int[] testScores;
testScores = new int[] {4,7,2};                                // the right hand is the anonymous array
Simple arrays

public class Array1 {

   public static void main(String[] args) {

      // array declaration and initialization
      int[] counter;
      counter = new int[3];

      // declaration and initialization in one statement
      String[] names = { "Paul", "Lorraine", "Dominic", "Jessica" };

      // add some data to the counter array
      counter[0] = 0;
      counter[1] = 1;
      counter[2] = 2;

      System.out.println("Counter: " + counter[0] + " " + counter[1] + " " + counter[2] + "\n");

      for (int x=0; x < names.length; x++)   // Use the length variable to get number of elements
      {
         System.out.println("Name: " + names[x]);
      }
   } // END MAIN
}

Note: arrays have a length variable that contains the number of elements.

multi-dimensional array examples class arrayTest {

   public static void main(String[] args) {

      int array1[][] = { {1,2,3}, {4,5,6} };
      int array2[][] = { {1,2}, {3}, {4,5,6} };

      buildOutput(array1);
      System.out.println();
      buildOutput(array2);
   }

   public static void buildOutput ( int a[][] ) {
      for ( int i = 0; i < a.length; i++ ) {
         for ( int j = 0; j < a[i].length; j++)
            System.out.print(a[i][j] + " ");

         System.out.println();

      }
   }
}
Passing arrays to methods class arrayTest {

public static void main(String[] args) {

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

   System.out.print("Orginal array values: ");
   for (int i = 0; i < a.length; i++)
      System.out.print( a[i] + " ");

   System.out.println();

   // array is passed to by-reference
   modifyArray(a);

   System.out.print("Now changed to: ");
   for (int i = 0; i < a.length; i++)
      System.out.print( a[i] + " ");

   System.out.println("\n\nElement a[3] is now: " + a[3]);

   // array elements are passed by-value;
   modifyElement (a[3]);

   System.out.println("Element a[3] has been changed to: " + a[3]);

   }

   // whole array are passed by-reference
   public static void modifyArray (int b[]) {
      for (int j = 0; j < b.length; j++)
         b[j] *= 2;
   }

   // array elements are passed by-value
   public static void modifyElement (int e)
   {
      e *=2;
   }
}

Manipulating Arrays

To manipulate Arrays in Java we can use the utility class java.util.Arrays (sorting, searching, etc), ArrayList's are alternate methods for manipulating collections of data.

Type of Functionality Arrays Class methods List Interface methods
Comparison compare (Java 9)
compareUnsigned (Java 9)
deepEquals
equals
equals
isEmpty
Searches binarySearch
misMatch (Java 9)
contains
containsAll
indexOf
lastIndexOf
Data Manipulation deepHashCode
deepToString
fill
hashCode
parallelPrefix (Java 8)
parallelSort (Java 8)
parallelSetAll (Java 8)
setAll (Java 8)
sort
toString
add
addAll
clear
get
hashCode
remove
removeAll
replaceAll
retainAll
set
size
sort
Data Transformation asList
copyOf
copyOfRange
spliterator (java 8)
stream (Java 8)
copyOf (Java 10)
iterator
listIterator
of (Java 9)
spliterator (Java 9)
subList
toArray

Some examples of the above are below, use the Java documentation or have a play around to get more familiar with these methods

Comparison Examples
String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"};

String[] names2 = {"Will", "Graham", "Moore", "Arthur", "Norman"};

String[] names3 = {"Will", "Graham", "Moore", "Arthur"};

String[] names4 = names1;

String[] names5 = {};

// Equals checks if the arrays are the same (same reference)
System.out.println(names1.equals(names2));                  // contents are the same but they are different arrays
System.out.println(names1.equals(names3));                  // both contents and arrays are different
System.out.println(names1.equals(names4));

// Arrays.compare checks the contents of the arrays, it does not care if they are not the same array (same reference)
System.out.println(Arrays.compare(names1, names2));         // only checks that the contents are the same
System.out.println(Arrays.compare(names1, names3));         // contents are not the same
System.out.println(Arrays.compare(names1, names4));         // contents are the same

// We have to convert to a list before we can use the List.isEmpty method
System.out.println(Arrays.asList(names1).isEmpty());
System.out.println(Arrays.asList(names5).isEmpty());        // the array has to be empty not NULL
Searching Examples
int[] numbers1 = {0, 1, 2, 3, 4, 5, 6};                           // sorted array
int[] numbers2 = {6, 3, 2, 1, 5, 0, 4};                           // unsorted array

String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"};
String[] names2 = {"Will", "Graham", "Moore", "Arthur", "Norman"};

System.out.println(Arrays.binarySearch(numbers1, 3));             // display the index where the pattern matched
System.out.println(Arrays.binarySearch(numbers2, 3));             // arrays must be sorted for the binarySearch to work, this display -7

Arrays.sort(names1);
System.out.println(Arrays.toString(names1));                      // list is now in sorted order
System.out.println(Arrays.binarySearch(names1, "Arthur"));        // the array MUST be sorted

System.out.println(Arrays.asList(names2).contains("Moore"));      // a LIST is a ordered collection (ordering is as they were entered) of objects that contain duplicates
System.out.println(Arrays.asList(names2).indexOf("Norman"));

System.out.println(Arrays.toString(names2));
Data Manipulation Examples
int[] numbers1 = {0, 1, 2, 3, 4, 5, 6};                     // sorted array

String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"};

Arrays.fill(numbers1, 0);
System.out.println(Arrays.toString(numbers1));

Arrays.setAll(numbers1, p -> p = 1);                        // you could have complex lambda (operator) here
System.out.println(Arrays.toString(numbers1));

// You can use some of the List methods as well
System.out.println(Arrays.asList(names1).size());
System.out.println(Arrays.asList(names1).get(1));

Arrays.asList(names1).replaceAll(p -> p = "Paul");          // this updates the array using the List interface
System.out.println(Arrays.toString(names1));
Data Transformation Examples
int[] numbers1 = {0, 1, 2, 3, 4, 5, 6};                                  // sorted array

String[] names1 = {"Will", "Graham", "Moore", "Arthur", "Norman"};

int[] numbers2 = Arrays.copyOf(numbers1, numbers1.length);               // returns the copied number of elements
System.out.println(Arrays.toString(numbers2));

int[] numbers3 = Arrays.copyOf(numbers1, 3);                             // you can just copy a subset of the array
System.out.println(Arrays.toString(numbers3));

 System.out.println(Arrays.asList(names1).subList(1, 3).toString());     // this returns a List, from index, to index (excluding), notice we did not pickup Arthur at index 3