Menu
Coddy logo textTech

Array

Lesson 10 of 16 in Coddy's Strings and Arrays in Java course.

Arrays are used to store multiple values in a single variable.

To declare an array, define the variable type with square brackets:

int[] numbers;

Just like a string, an array is also a non-primitive type.

To initialize the array values, place the values in a comma-separated list, inside curly braces:

int[] numbers = {1, 5, 12, 435};

The same goes for any type, for example, a String one:

String[] names = {"Bob", "Alice", "John"};

To get the length of an array, use the length property:

System.out.println(names.length); // Outputs 3

Notice that here length is a property and not a method, like in String.

quiz iconTest yourself

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

quiz iconTest yourself

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

challenge icon

Challenge

Easy

You are given a code, your tasks are:

  1. Declare and initialize an array (of type double) named coolNums with the values: 3.14, 1.68, 9.99 (in this order!)
  2. Print the length of the array you declared.

Try it yourself

class Main {
    public static void main(String[] args) {
        // Write code here
        
        // Don't change below this line
        System.out.print(coolNums[0]);
        System.out.print(", ");
        System.out.print(coolNums[1]);
        System.out.print(", ");
        System.out.print(coolNums[2]);
    }
}

All lessons in Strings and Arrays in Java