Arrays

  • Declaring and Creating Arrays

  • Accessing array elements

  • Console Input and Output of arrays

  • Copying arrays

  • The java.util.Arrays class

Declaring and creating arrays

5.6
4.5
1.37
8.98
11.345
0.66

arr[5]

arr[4]

arr[3]

arr[2]

arr[1]

arr[0]

double[] arr = new double[6];
reference

arr

Array reference variable

Array element 

at index 3

Element value

Default datatype values

  • numeric primitive types - 0

  • char - '\u0000' (null character)

  • boolean - true/false

  • Strings/objects - null

  • when space for an array is allocated, array size must be specified

  • array size cannot be changed afterwards

  • array size is obtained via:

arr.length

Array size

  • Java has a shorthand notation, known as array initializer, which combines declaring, creating and initializing in one step:

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

Array initializer

Accessing array elements

Array indexed variables

  • elements are accessed through an index

  • array indices are 0-based: start from 0 and end at arr.length - 1

  • each element is represented with the following syntax known as an indexed variable:

 

arr[3]

Console Input and Output of arrays

Scanner s = new Scanner(System.in);
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
    int num = s.nextInt();
    arr[i] = num;
}

Input array elements

  • using a for loop we assign our input to each indexed variable of the array

int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

Output array elements

  • for loop

int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) {
    System.out.println(arr);
}
  • foreach loop

Copying Arrays

int[] sourceArr = {1, 2, 3, 4, 5};
int[] targetArr = new int[sourceArr.length];
Definition:
System.arraycopy(sourceArr, sourcePos, targetArr, targetPos, length)

System.arraycopy(sourceArr, 0, targetArr, 0, sourceArr.length);
  • declare and initialize source and target array

  • using a for-loop

for (int i = 0; i < sourceArr.length; i++) {
    targetArr[i] = sourceArr[i];
}
  • using System.arraycopy(...)

The java.util.Arrays class

// sort an array
Arrays.sort(arr);

// search in an array
Arrays.binarySearch(arr, key);

// convert array to list
Arrays.asList(arr);

// from java 8
Arrays.stream(arr);
  • contains various methods for manipulating arrays

Questions?