Array Creation and Access

Array Creation and Access

Introduction to Arrays

  • An array is a data structure that can store a fixed size sequential collection of elements of the same type.
  • To use arrays in Java, you need to declare variable type with [] or [ ].
  • You can initialise an array using the new keyword followed by the data type and the size of the array in square brackets.

Array Creation

  • Zero-based numbering is used for indexing arrays, meaning that the first element is found at index 0.
  • An array in Java can be created using the syntax dataType[] arrayRefVar = new dataType[arraySize]; Or simply, dataType[] arrayRefVar; followed by arrayRefVar = new dataType[arraySize];.

Accessing Array Elements

  • Arrays offer a convenient means of grouping related information.
  • You can access an element in an array by referring to the index number.
  • To access elements from the array, you use indices. For example array[0] will access the first element.
  • You can change an element with something like array[0] = newValue;.

Array Limitations and Advantages

  • The length of an array is established when the array is created and array lengths are immutable.
  • Arrays can contain any type of element, including primitives and references to objects.
  • Arrays can hold many values under a single name, and you can access the values by referring to an index number.
  • However, array indexes are zero-based: the first array element is at index 0.

Multi-Dimensional Arrays

  • Java supports multidimensional arrays, which are arrays of arrays.
  • A 2D array is created the same way as a one dimensional array: dataType[][] arrayRefVar = new dataType[size1][size2];.
  • In a two-dimensional Java array, we can use the code a[i][j] to represent the element at the second position of the first position.
  • Arrays can be multidimensional with each level of array holding its own length property. This allows for a very flexible and practical way to group data.

By using these notes to revise, you will improve your understanding of arrays in Java and increase your problem-solving ability when dealing with complex data structures.