Menu
Coddy logo textTech

Declaring Arrays

Part of the Fundamentals section of Coddy's Java journey — lesson 58 of 73.

An array is a collection of items, and it can contain values of different types, such as numbers, strings, or even other arrays. Arrays are created using square brackets [], and the items inside the array are separated with commas.

Here is an example of how to create an array:

int[] numbers = {1, 2, 3, 4, 5};

To check the length of the array, we can use the .length field:

int length = numbers.length;

.length is a field, not a method — so it is accessed without parentheses ().

The variable length will hold 5 because there are 5 elements in the array.

Another way to create an array using the new keyword followed by the array type and size:

int[] numbers = new int[5];

Creates an array of 5 integers, all initialized to 0

challenge icon

Challenge

Easy

Create an array called shoppingList that contains the following items: bread, eggs, milk, and butter.

Cheat sheet

Arrays are collections of items created using square brackets [] with items separated by commas:

int[] numbers = {1, 2, 3, 4, 5};

Check array length using the .length field:

int length = numbers.length;

Create arrays with the new keyword:

int[] numbers = new int[5]; // Creates array of 5 integers, all initialized to 0

Try it yourself

public class Main {
    public static void main(String[] args) {
        // Create the shoppingList array here
        
        
        // Don't change the code below
        System.out.println("Shopping List:");
        for (int i = 0; i < shoppingList.length; i++) {
            System.out.println(shoppingList[i]);
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals