The element type in an array is unique and can store only one type, not multiple types of data.

An array is a reference type.

Define an array

type[] arrayName; // This is recommended to define array type arrayName[];Copy the code

Initializing an array

  • Static initialization
    • At initialization, the programmer displays the initial values for each array element, and the system determines the length of the array.
type[] arrayName = new type[] {element1, element2, element3}; Int [] a = new int[]{5, 6, 7}; int[] b = {6, 7, 8}; Object[] obj = new String[]{"hello", "world"};Copy the code
  • Dynamic initialization
    • At initialization, the programmer only specifies the length of the array, and the system assigns initial values to the array elements.
    • An integer (bype, short, int, long) with an initial value of 0
    • Floating-point type (float, double). Array elements have an initial value of 0.0
    • Character type (char), array element initial value ‘\u0000’
    • Boolean. Array elements have an initial value of false
    • A reference type (class, interface, and array) with an initial value of NULL for array elements
type[] arrayName = new type[length]; Int [] a = new int[3]; Object[] obj = new String[2];Copy the code

Use an array

  • Array indexes start at 0, the first element is indexed to 0, and the last element is indexed to the array length minus 1.
  • If the index specified when accessing an array element is less than 0, or greater than or equal to the length of the array, the compiler does not get any errors, but runs an exception: Java. Lang. ArrayIndexOutOfBoundsException: N (array index cross-border exception), abnormal information after N is program trying to access an array index.
int[] b = {6, 7, 8}; Object[] obj = new String[]{"hello", "world"}; System.out.println(b[0]); //6 System.out.println(obj[1]); //world system.out.println (obj[2])Copy the code