CodeBlanks Logo Icon CodeBlanks

Declaring arrays

Learn to declare arrays with new int[n].

Declaring arrays

An array is a fixed-size data structure of the same type. With new int[n] you create an n-element array:

int[] arr = new int[5];
System.out.println(arr.length);  // 5

Here arr is a 5-element int array; all elements start at 0. arr.length gives the array's size (no parens). The size cannot change after creation, which is why it is called fixed-size.

Array declaration forms

There are two main ways to declare an array:

// 1. new with a size
int[] a = new int[5];
// 2. literal with values
int[] b = {10, 20, 30};

In the first form all elements start at 0. In the second, elements are listed in braces separated by commas; the size is the value count. Both give the size via arr.length.

Practice Declare an array and print its size

Write a Main class with a main method. Assign new int[5] to int[] arr. Print the array's size with System.out.println(arr.length).

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int[] arr = new int[5];
        System.out.println(arr.length);
    }
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many elements does new int[5] create?

  • 4
  • 5 Correct answer
  • 6
  • 0

Explanation: new int[5] creates a five-element array.

2 Complete the array declaration

Question
int[] arr = new int[5____;
Answer
int[] arr = new int[5];

Explanation: new int[5] declares a five-element array.

3 Match the array declaration concepts

Term Meaning
int[] Type
new int[5] Five elements
arr.length Size
{1, 2} Literal

All lessons in Beginner