Arrays must be declared and initialized before they can be used. This process involves defining the array type, creating the array, and optionally assigning initial values to its elements. Let’s explore how to declare and initialize arrays with specified sizes or initial values in Java.
To declare an array, you specify the type of elements it will hold, followed by square brackets ([]
) to denote it as an array type. Here’s the basic syntax for declaring an array:
int[] numbers; // An array of integers
String[] names; // An array of strings
At this point, numbers
and names
are just declared as arrays but have not been initialized with actual storage.
After declaring an array, you can use the new
keyword to allocate memory for a fixed number of elements. Each element in the array is then assigned a default value (0 for numeric types, false
for boolean, and null
for object types).
int[] numbers = new int[5]; // Initializes an integer array with 5 elements, each set to 0 by default
String[] names = new String[3]; // Initializes a String array with 3 elements, each set to null by default
In the numbers
array above, numbers[0]
through numbers[4]
are set to 0
by default because int
is a numeric type.
Instead of initializing an array with a specific size, you can also directly initialize it with specified values using curly braces {}
. This approach automatically sets the array size to match the number of provided values.
int[] numbers = {1, 2, 3, 4, 5}; // Array of 5 integers
String[] names = {"Alice", "Bob", "Charlie"}; // Array of 3 strings
This method is convenient when you already know the elements you want to include in the array.
public class ArrayExample {
public static void main(String[] args) {
// Declaration with size initialization
double[] prices = new double[4]; // Array with default values (0.0 for doubles)
prices[0] = 19.99;
prices[1] = 29.99;
// Declaration with specific values
char[] vowels = {'A', 'E', 'I', 'O', 'U'}; // Array of 5 characters
// Accessing elements
System.out.println("First price: " + prices[0]); // 19.99
System.out.println("First vowel: " + vowels[0]); // A
}
}
In Java, you can also initialize arrays based on dynamic conditions, like values calculated at runtime:
int size = getSizeFromUser(); // Assuming this method gets a size from user input
int[] dynamicArray = new int[size]; // Array with a user-specified size
for (int i = 0; i < dynamicArray.length; i++) {
dynamicArray[i] = i * 10; // Populating the array with calculated values
}