import ballerina/io;public function main() {
    int[] a = [];
    io:println(a.length());
    int[] b = [1, 2, 3, 4, 5, 6, 7, 8];
    io:println(b[0]);
    io:println(b.length());
    b[999] = 23;
    io:println(b[999]);
    io:println(b.length());
    int[][] iarray = [[1, 2, 3], [10, 20, 30], [5, 6, 7]];
    io:println(iarray.length());
    io:println(iarray[0].length());
    iarray = [];
    int[] d = [9];
    iarray[0] = d;
    io:println(iarray[0][0]);
    int[5] e = [1, 2, 3, 4, 5];
    io:println(e.length());
    int[*] g = [1, 2, 3, 4];
    io:println(g.length());
}

Arrays

Arrays are mutable lists of values of dynamic length, where each member in the list is of the same type. A fixed length array can be created by specifying the length of the array at the time of declaration.

import ballerina/io;
public function main() {
    int[] a = [];
    io:println(a.length());

Create an int array of length 0.

    int[] b = [1, 2, 3, 4, 5, 6, 7, 8];
    io:println(b[0]);
    io:println(b.length());

Create an array specifying an array literal.

    b[999] = 23;
    io:println(b[999]);
    io:println(b.length());

Unless the length is explicitly specified or is expected to be inferred, arrays are unbounded in length. They can grow up to any length based on the given index. In this example, the length of the array is 1000.

    int[][] iarray = [[1, 2, 3], [10, 20, 30], [5, 6, 7]];
    io:println(iarray.length());
    io:println(iarray[0].length());

Initialize a two dimensional int array.

    iarray = [];

Initialize the outermost array to an empty array.

    int[] d = [9];
    iarray[0] = d;

Add a new array as the first element.

    io:println(iarray[0][0]);

Print the first value of the two-dimensional array.

    int[5] e = [1, 2, 3, 4, 5];
    io:println(e.length());

Create an int array with the fixed length of five.

    int[*] g = [1, 2, 3, 4];
    io:println(g.length());
}

To infer the size of the array from the array literal, use the following syntax. The length of the array is set to four here.

# To run this sample, navigate to the directory that contains the
# `.bal` file and execute the `ballerina run` command.
$ ballerina run arrays.bal
0
1
8
23
1000
3
3
9
5
4