Start learning free

LESSON 91 OF 410 · ARRAYS I

Static Arrays in Java: Creating Fixed-Size Arrays

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In Java, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

We create a static array by using the keyword new, then writing the data type of the elements and the array's length inside []:

String[] arrayOfStrings = new String[3];

In this program we created an array named arrayOfStrings that consists of 3 String items.

These 3 items are null (no value given yet) initially.


Creation & Initialization:

There is a way to initialize an array at creation by using the = operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

String[] arrayOfStrings = {"AlgoCademy", "coding", "static arrays"};

We created an array named arrayOfStrings which consits of 3 String items: "peanut butter", "jelly" and "bread".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · ARRAYS I

    Static Arrays in Java, explained

    What a static array is

    An array stores several values of the same type under one name. In Java, an array has a fixed length: you choose how many elements it holds when you create it, and that number never changes. This is why the arrays in this lesson are called static arrays, or fixed-size arrays. If you need a collection that grows, Java offers ArrayList, which is a different type.

    Two facts define every Java array:

    • All elements have the same type, such as int or String.
    • The length is fixed at creation, and elements are numbered from 0 to length - 1.

    Creating an array with a length

    Use new, the element type and the length in square brackets:

    String[] arrayOfStrings = new String[3];
    int[] numbers = new int[20];
    

    The first line creates an array of three String slots, and the second creates an array of twenty int slots. The brackets after the type in the declaration (String[], int[]) say "an array of this type", and the number goes after new.

    The new array is never empty. Every slot gets the default value for its type:

    Element typeDefault value
    int, long, short, byte0
    double, float0.0
    booleanfalse
    charthe character with code 0
    String and other objectsnull

    So new int[20] holds twenty zeros, and new String[3] prints as [null, null, null] when passed to Arrays.toString. A null element means "no object yet": calling a method on it, such as arrayOfStrings[0].length(), throws a NullPointerException until you store a string there.

    Creating and filling an array at once

    When you already know the values, list them in braces, separated by commas:

    String[] fruits = {"mango", "kiwi", "grapefruit"};
    

    This is the array initializer. The compiler counts the values, so you do not write the length: fruits has length 3. The same array can be written with the longer form new String[]{"mango", "kiwi", "grapefruit"}. That longer form is required when the array is not part of a declaration. For example, nums = {1, 2, 3}; on its own line does not compile, while nums = new int[]{1, 2, 3}; does.

    The exercise, step by step

    1. Create an int array of 20 elements named numbers, with new int[20]. The length is fixed at 20 and every element is 0.
    2. Create a String array named fruits with an initializer in braces holding "mango", "kiwi" and "grapefruit".
    int[] numbers = new int[20];
    String[] fruits = {"mango", "kiwi", "grapefruit"};
    

    Checking the result:

    System.out.println(numbers.length);   // 20
    System.out.println(numbers[19]);      // 0
    System.out.println(fruits.length);    // 3
    System.out.println(fruits[2]);        // grapefruit
    

    Reading, writing and the length

    Use the index in square brackets to read or change an element. The first element is index 0 and the last is length - 1:

    numbers[0] = 5;
    System.out.println(numbers[0]);     // 5
    System.out.println(fruits[0]);      // mango
    

    The length is the field length, with no parentheses: numbers.length. Writing numbers.length() does not compile and gives cannot find symbol. (Strings use length() with parentheses, and lists use size(), which is a common source of mix-ups.)

    To visit every element, use a loop:

    for (String fruit : fruits) {
        System.out.print(fruit + " ");
    }
    

    This prints mango kiwi grapefruit . To show the whole array at once, use Arrays.toString(fruits) from java.util, which gives [mango, kiwi, grapefruit]. Passing the array straight to println does not do this: it prints the array's type and an identity code, something like [Ljava.lang.String;@ followed by a number.

    Why "static": the length cannot change

    There is no way to add a 21st element to numbers. If you need more room, create a new, larger array and copy the old values into it. The helper Arrays.copyOf does this in one call:

    int[] primes = {2, 3, 5};
    int[] bigger = Arrays.copyOf(primes, 5);   // [2, 3, 5, 0, 0]
    

    The new slots get default values, and primes itself is unchanged. When you need a collection that grows and shrinks often, use an ArrayList.

    Common mistakes

    • Using an index outside the array. The valid indexes of numbers are 0 to 19. numbers[20] = 1; throws ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20. Java checks every access, so it never silently reads memory beyond the array.
    • Thinking the first element is at index 1. It is at index 0.
    • A negative length. new int[-1] throws a NegativeArraySizeException at run time.
    • Using the initializer after declaration. Braces alone only work in the declaration, as shown above.
    • Treating null elements as strings. A fresh new String[3] holds three null values, not three empty strings.
    • Copying with =. int[] alias = primes; makes a second name for the same array, not a copy. Changing alias[0] also changes primes[0]. Use Arrays.copyOf to make an independent copy.

    Key takeaways

    • A static array has a fixed length and a single element type. Create it with new Type[length] or with braces.
    • New arrays are filled with defaults: 0, false or null.
    • Indexes run from 0 to length - 1, and the length is the field length.
    • To change the size, create a new array and copy the data.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free