![]() |
VOOZH | about |
To declare an array, specify the data type followed by square brackets [] and the array name. This only declares the reference variable. The array memory is allocated when you use the new keyword or assign values.
Complete working Java example that demonstrates declaring, initializing, and accessing arrays
Array elements are: 10 20 30 40 50 First element is: 10
Before using an array, you must declare it by specifying the data type and the array name.
Syntax:
dataType[] arrayName;
dataType arrayName[];
Examples:
// Declares an integer array
int[] numbers;// Declares a string array
String[] names;// Declares a double array
double[] scores;
After declaration, arrays must be initialized with values. There are several ways to do this:
Values are assigned to the array at the time of declaration.
int[] numbers = {10, 20, 30, 40, 50};
String[] fruits = {"Apple", "Banana", "Mango"};
The array is created first with a specific size, and values are assigned later.
int[] numbers = new int[5]; // Array of size 5
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Ideal for larger arrays or sequential values:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1; // Fills array with 1, 2, 3, 4, 5
}
Java 8 introduced IntStream to initialize integer arrays efficiently.
1. Using IntStream.range(start, end): generates values from start (inclusive) to end (exclusive).
int[] arr = java.util.stream.IntStream.range(1, 5).toArray();
// Output: 1, 2, 3, 4
2. Using IntStream.rangeClosed(start, end): Generates values from start to end (inclusive).
int[] arr2 = java.util.stream.IntStream.rangeClosed(1, 4).toArray();
// Output: 1, 2, 3, 4
3. Using IntStream.of(): Directly initializes an array with specified values.
int[] arr3 = java.util.stream.IntStream.of(5, 10, 15).toArray();
// Output: 5, 10, 15
You can access and manipulate elements using indices, starting from 0:
int[] arr = {1, 2, 3, 4};
System.out.println(arr[0]); // Output: 1
The length property returns the number of elements in the array:
System.out.println("Array length: " + arr.length); // Output: 4