Declaring arrays
- Java course
- Beginner
- Lesson 53/116
- 4 min
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); // 5Here 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
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
int[] arr = new int[5____;
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 |