Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Arrays: T[] and new T[n]

A Java array is a fixed-length object storing elements of one component type. Learn the T[] declaration, creation with new T[n], zero-based indexing, and shared references.

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

Syntax

T[] name = new T[n];
int[] values = {1, 2, 3};
name[index]
name.length

In T[] / new T[n], T[] denotes an array type, while new T[n] creates an array of length n. Here T is a placeholder for a type such as int or String, not an arbitrary generic type parameter: new T[n] is illegal when T is a type parameter. Writing int[] values; alone declares a variable but creates no array.

New array elements receive default values: numeric zero, false for boolean, and null for references. The field length, not a length() method, gives the unchangeable length; elements can be changed. Assigning an array variable copies the reference, not the elements.

Access with values[i] requires an index from 0 through values.length - 1. Outside this range, ArrayIndexOutOfBoundsException is thrown; access through null causes NullPointerException. A negative creation size causes NegativeArraySizeException; size zero is valid.

The type int[][] means an array of arrays, so rows may have different lengths or be null. Reference arrays are covariant: Object[] items = new String[1]; is valid, but items[0] = new Object(); causes ArrayStoreException because the actual array accepts only references compatible with String.

Examples

public class ArrayDemo {
    public static void main(String[] args) {
        int[] values = new int[3];
        values[0] = 4;
        values[1] = 7;
        int[] same = values;
        same[1] = 8;
        int sum = 0;
        for (int value : values) {
            sum += value;
        }
        System.out.println(values.length);
        System.out.println(values[2]);
        System.out.println(sum);
    }
}

Result

3
0
12

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