Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Array initializer

An array initializer creates an array from values enclosed in braces. The number of entries determines its length.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

int[] values = {1, 2, 3,};
values = new int[] {4, 5};
int[] empty = {};
int[][] rows = {{1, 2}, {3}};

An array initializer is a comma-separated list of values inside {}. Writing {} creates an empty array; a trailing comma is allowed and ignored.

A field or local variable declaration can use int[] values = {1, 2};. A bare brace initializer cannot appear on the right-hand side of a later assignment: values = {4, 5}; is invalid. You can use an array creation expression, as in values = new int[] {4, 5};, or assign a compatible array reference you already have or obtain from a method call.

Values are evaluated from left to right and must be assignment-compatible with the component type. Nested initializers create subarrays, which may have different lengths.

Examples

public class Main {
    public static void main(String[] args) {
        int[] values = {4, 7, 9,};
        System.out.println(values.length);
        System.out.println(values[0] + values[2]);
        values = new int[] {2, 5};
        System.out.println(values.length);
    }
}

Result

3
13
2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources