In Java, an array is a fixed-size data structure that holds multiple values of the same type. There are different ways to declare and initialize an array.
Declaration of an Array
Before using an array, it must be declared. The syntax is:
dataType[] arrayName; // Recommended syntax
// OR
dataType arrayName[]; // Valid but less preferred
Example:
int[] numbers; // Declaring an integer array
String[] names; // Declaring a string array
At this stage, the array is just declared but not initialized.
Initializing an Array
After declaring an array, we must allocate memory for it. There are multiple ways to do this:
a) Using the new
Keyword (Fixed Size)
int[] numbers = new int[5]; // Creates an array of size 5 with default values (0)
The array size must be specified while using new
.
b) Declaring and Assigning Values Directly
int[] numbers = {10, 20, 30, 40, 50}; // Size is automatically determined
String[] names = {"Alice", "Bob", "Charlie"};
This method is preferred when we already know the values.
c) Initializing with a Loop (Dynamic Values)
int[] numbers = new int[5]; // Array of size 5
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i * 10; // Assigning values dynamically
}
This method is useful when we generate values at runtime.
Example Program: Declare and Initialize an Array
public class MasterBackend {
public static void main(String[] args) {
// Declaration and initialization
int[] ages = {18, 20, 22, 24, 26};
// Printing array elements
System.out.println("Ages of students:");
for (int i = 0; i < ages.length; i++) {
System.out.println("Student " + (i + 1) + ": " + ages[i]);
}
}
}