Java 11 Developer Certification - Java Arrays - Declaration and Initialization

October 28, 2020

What we are covering in this lesson

  1. What are arrays
  2. Declaring an array
  3. Creating an array
  4. Examples of array declarations and initializations

What are arrays

We have been working through out with arrays. The String[] args parameter in main method is a single dimensional String array.

  • An array is a collection of objects that holds a fixed number of values of a single type.
  • The length of an array has to be known beforehand, when the array is created.
  • An array can reference duplicate values.
  • An array can be one or two dimensional. Multi dimensional arrays can be created by creating array or arrays.
  • We can store a subclass object in an array, declared to be the type of the superclass or interface, hence supporting polymorphism. For e.g., an array of CharSequence can store references to String and StringBuilder or both.
  • Array index always starts with 0 and last index is (length of array - 1)

Declaring an array

When you declare an array,

  • you have to define the type of the elements in the array
  • the brackets [] are the array identifiers

    • One set of [] on declaration side is required, to identify 1-dimensional array
    • the brackets can be to the right of the declared type
    • the brackets can also be to the right of the declared variable name, but this is not a standard way of coding.
    • adding brackets to both the right of the type and variable name will declare a two-dimensional array.
  • The type of array can be either primitive type, a class or an interface.
  • You never include the size of the array on the left side (declaration side).

Below we have some valid array declarations.

int[] intArray;
short shortArray[];
int a, b[], c;
int[] a, b, c[];    //c will be 2-D array
String[] strArray[];    //again, 2-D string array

//Below are invalid declarations
//int[2] iArray; //gives compiler error as size cannot be part of declaration  
//int iArray[2]; //gives compiler error as size cannot be part of declaration
//int a, float[] b; //different types on single line not allowed

Creating an array

We can create array by the following ways

  • Using new operator
  • Using array initializer

Lets look at both the techniques of array creation

Creating array using new operator

We can create array in the following way using the new operator int[] intArray = new int[100]; //Creates an array of 100 int elements, all initialized to 0 String[] strArray = new String[100]; //Creates an array of 100 String elements, all initialized to null

Notes:

  • When creating array of objects, we are not calling the Object constructor, and so no parenthesis after the new statement.
  • We must define the size of the array in brackets. This size cannot be changed later.
  • JVM automatically assigns default values when arrays are created using new operator

    • Numeric primitives default to 0
    • Boolean primitives default to false
    • References, including primitive data type wrappers, are set to null

Creating array using array initializer

This is a shortcut that allows creation and initialization of each element in an array, in a single statement.

String[] strArray = {"1", null, "2", "3"}; //4 elements string array int[] intArray = {1,2,3,4,5} // 5 elements int array

Note that the array initializer can only be used in the same statement as the declaration.

Examples of array declarations and initializations

Below are some examples of valid array creation statements

int[] intArr = new int[50]; //50 elements int array
int[] intArr2 = null; //an array can be set to null

String[] strArr;    //Only declaration
strArr = new String[10]; //intialization

int[] intArr3, anotherArr = new int[10]; //only the second array is initialized, intArr3.length throws error

int[] arr1, arr2 = arr1 = new int[50]; //both arrays initialized here

String[] sArr = {}; //setting array to 0 length array
String[] sArr2[] = {{"1", "2"}, {"3", "4"}}; //2D array

Object o = new int[10]; //valid
int a[] = new int[]{1,2,3}; //combination of array initializer and new operator, no need to mention array size in brackets

int [][] twoDArray = new int[2][]; //first dimension is required to have a size

Now lets have a look at some of the invalid array declarations.

String[] s1 = new String()[3]; //parenthesis incorrect
String[3] s2 = new String[]; //size should be on right side
int a[] = int[]{1,2,3}; // restatement of int[] not required on right side
int b[] = new int[3]{1,2,3}; //size + array initializer is invalid, array initializer defines the size

String[] s3;
s3 = {"1", "2", "3"}; //cannot use array intializer on separate line

int[] i1, i2 = i1 = {1,2,3}; //invalid without new. Array initializer cannot be used in compound statement

int[][] twoD = new int[][2]; //first dimension should have size

int abc[] = new int[10][]; //initialize 2D and assigning to 1D array is invalid

Lets have a look at a simple array example in java code

package maxCode.online.Arrays;

import java.util.Arrays;

public class ArrayExample {
	public static void main(String[] args) {
        // elements initialized to null
        Integer[] integerArray = new Integer[5]; //Integer array

        // elements initialized to 0
        int[] intArray = new int[5]; //int array

        // Arrays.toString() prints elements as comma delimited String
        System.out.println("intArray = " + Arrays.toString(intArray));
        System.out.println("integerArray =" + Arrays.toString(integerArray));

        // loop condition uses length attribute of one of the arrays.
        for (int i = 0; i < intArray.length; i++) {
            // Set data on arrays, auto-boxing occurs for integerArray
            integerArray[i] = intArray[i] = (i + 1);
        }
        
        System.out.println("\nAfter Loop");
        System.out.println("intArray = " + Arrays.toString(intArray));
        System.out.println("integerArray =" + Arrays.toString(integerArray));

        // Access a single element in array
        intArray[2] = 10;
        integerArray[0] = 99;

        System.out.println("\nFinal Values");

        System.out.println("intArray = " + Arrays.toString(intArray));
        System.out.println("integerArray =" + Arrays.toString(integerArray));

        // Create new int[] variable reference and assign it intArray
        int[] intArray2 = intArray;

        // Create new Integer[] variable reference and assign it intArray
        Integer[] integerArray2 = integerArray;

        System.out.println("\nAgain Final Values");

        System.out.println("intArray = " + Arrays.toString(intArray));
        System.out.println("integerArray =" + Arrays.toString(integerArray));

        System.out.println("\nPrint Arrays");

        // Printing the array references confirm that these variables
        // reference the same set of elements
        System.out.println("intArray = " + intArray);
        System.out.println("intArray2 = " + intArray2);
        System.out.println("integerArray = " + integerArray);
        System.out.println("integerArray2 = " + integerArray2);

        // Make a change to data on first array references
        integerArray[0] = 55;
        intArray[0] = 66;

        // Make a change to data on second array references
        integerArray2[1] = 77;
        intArray2[1] = 88;

        System.out.println("\nPrint Array Values");

        // You can see both references show the data changes
        System.out.println("integerArray = " + Arrays.toString(integerArray));
        System.out.println("integerArray2 = " + Arrays.toString(integerArray2));
        System.out.println("intArray = " + Arrays.toString(intArray));
        System.out.println("intArray2 = " + Arrays.toString(intArray2));
	}
}

Output

intArray = [0, 0, 0, 0, 0]
integerArray =[null, null, null, null, null]

After Loop
intArray = [1, 2, 3, 4, 5]
integerArray =[1, 2, 3, 4, 5]

Final Values
intArray = [1, 2, 10, 4, 5]
integerArray =[99, 2, 3, 4, 5]

Again Final Values
intArray = [1, 2, 10, 4, 5]
integerArray =[99, 2, 3, 4, 5]

Print Arrays
intArray = [I@73a8dfcc
intArray2 = [I@73a8dfcc
integerArray = [Ljava.lang.Integer;@ea30797
integerArray2 = [Ljava.lang.Integer;@ea30797

Print Array Values
integerArray = [55, 77, 3, 4, 5]
integerArray2 = [55, 77, 3, 4, 5]
intArray = [66, 88, 10, 4, 5]
intArray2 = [66, 88, 10, 4, 5]

The important thing to note here is that a change to an element referenced by one array, is reflected when the second array is printed, since both array variables are referencing the same set of objects.