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

An array is a reference type.

Define an array

type[] arrayName; Array type arrayName[]; array type arrayName[];

Initialize array

  • Static initialization

    • During initialization, the programmer displays the initial value of 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"};
  • Dynamic initialization

    • When initialized, the programmer only specifies the length of the array, and the system assigns initial values to the array elements.
    • Integer type (bype, short, int, long), array elements with an initial value of 0
    • Floating-point type (float, double) with an initial value of 0.0 for array elements
    • Character type (char), the initial value of array elements is ‘\u0000’
    • Boolean, array elements with an initial value of false
    • Reference types (classes, interfaces, and arrays) with array elements initially NULL
type[] arrayName = new type[length]; // int[] a = new int[3]; Object[] obj = new String[2];

Use an array

  • Array indexes start at 0, the first element has an index of 0, and the last element has an index of 1 minus the length of the array.
  • If an array element is accessed with an index value less than 0 or greater than or equal to the length of the array, the compiler will not experience any errors, but an exception occurs at runtime: 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]);// World System.out.println(obj[2])