Skip to content
On this page

Array Type

If we have a set of variables of the same type, for example, the grades of 5 students, we can write:

java
public class Main {
  public static void main(String[] args) {
    // Results of 5 students:
    int n1 = 68;
    int n2 = 79;
    int n3 = 91;
    int n4 = 85;
    int n5 = 62;
  }
}

But there is actually no need to define 5 int variables. Arrays can be used to represent a "set" int types. The code is as follows:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = new int[5];
        ns[0] = 68;
        ns[1] = 79;
        ns[2] = 91;
        ns[3] = 85;
        ns[4] = 62;
    }
}

To define a variable of array type, use the array type "type[]", for example, int[] . Unlike a single basic type variable, array variable initialization must use new int[5] to create an array that can hold 5 int elements.

Java arrays have several characteristics:

  • All elements of the array are initialized to default values, integer types are 0 , floating point types are 0.0 , and Boolean types are false ;
  • Once an array is created, its size cannot be changed.

To access an element in an array, you need to use an index. Array indexes start from 0 , for example, for a 5-element array, the index range is 0 ~ 4 .

You can modify an element in the array using an assignment statement, for example, ns[1] = 79; .

You can use ns.length to get the array size:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = new int[5];
        System.out.println(ns.length); // 5
    }
}

Arrays are reference types. When using indexes to access array elements, if the index exceeds the range, an error will be reported at runtime:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = new int[5];
        int n = 5;
        System.out.println(ns[n]); // Index n cannot be out of range
    }
}

You can also directly specify the initialized elements when defining the array, so that you don't have to write out the array size, but the compiler automatically calculates the array size. For example:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = new int[] { 68, 79, 91, 85, 62 };
        System.out.println(ns.length); // The compiler automatically infers that the array size is 5
    }
}

It can be further abbreviated as:

java
int[] ns = { 68, 79, 91, 85, 62 };

Note that arrays are reference types and their size is immutable. Let's observe the following code:

java
public class Main {
    public static void main(String[] args) {
        int[] ns;
        ns = new int[] { 68, 79, 91, 85, 62 };
        System.out.println(ns.length); // 5
        ns = new int[] { 1, 2, 3 };
        System.out.println(ns.length); // 3
    }
}

Has the array size changed? It looks like it has changed, but in fact it has not changed at all.

For the array ns , execute ns = new int[] { 68, 79, 91, 85, 62 }; , it points to an array of 5 elements:

     ns


┌───┬───┬───┬───┬───┬───┬───┐
│   │68 │79 │91 │85 │62 │   │
└───┴───┴───┴───┴───┴───┴───┘

When executing ns = new int[] { 1, 2, 3 }; it points to a new array of 3 elements:

     ns ──────────────────────┐


┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│   │68 │79 │91 │85 │62 │   │ 1 │ 2 │ 3 │   │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

However, the original 5-element array has not changed, it is just that they cannot be referenced through the variable ns .

String Array

If the array element is not a primitive type, but a reference type, what is the difference when modifying the array element?

Strings are reference types, so we first define an array of strings:

java
String[] names = {
    "ABC", "XYZ", "zoo"
};

For the array variable names of type String[] , it actually contains 3 elements, but each element points to some string object:

          ┌─────────────────────────┐
    names │   ┌─────────────────────┼───────────┐
      │   │   │                     │           │
      ▼   │   │                     ▼           ▼
┌───┬───┬─┴─┬─┴─┬───┬───────┬───┬───────┬───┬───────┬───┐
│   │░░░│░░░│░░░│   │ "ABC" │   │ "XYZ" │   │ "zoo" │   │
└───┴─┬─┴───┴───┴───┴───────┴───┴───────┴───┴───────┴───┘
      │                 ▲
      └─────────────────┘

Assign a value to names[1] , for example names[1] = "cat"; the effect is as follows:

          ┌─────────────────────────────────────────────────┐
    names │   ┌─────────────────────────────────┐           │
      │   │   │                                 │           │
      ▼   │   │                                 ▼           ▼
┌───┬───┬─┴─┬─┴─┬───┬───────┬───┬───────┬───┬───────┬───┬───────┬───┐
│   │░░░│░░░│░░░│   │ "ABC" │   │ "XYZ" │   │ "zoo" │   │ "cat" │   │
└───┴─┬─┴───┴───┴───┴───────┴───┴───────┴───┴───────┴───┴───────┴───┘
      │                 ▲
      └─────────────────┘

Note here that the string "XYZ" pointed to by names[1] has not changed. It is just that the reference of names[1] has been changed from pointing to "XYZ" to pointing to "cat" . The result is the string "XYZ" again. It cannot be accessed through names[1] .

After having a deeper understanding of "pointing", let's try to explain the following code:

java
public class Main {
    public static void main(String[] args) {
        String[] names = {"ABC", "XYZ", "zoo"};
        String s = names[1];
        names[1] = "cat";
        System.out.println(s); // Is s "XYZ" or "cat"?
    }
}

Summary

An array is a collection of the same data type. Once an array is created, its size is immutable;

Array elements can be accessed through indexes, but an error will be reported if the index is out of range;

Array elements can be value types (such as int ) or reference types (such as String ), but the array itself is a reference type;

Array Type has loaded