Arrays in Java: Declaration and Initialization

In Java, arrays are used to store multiple values of the same data type. Let's explore the declaration and initialization of arrays in-depth.

Declaration of Arrays:

To declare an array in Java, you specify the data type of the elements followed by square brackets.


// Declaration of an integer array
int[] integerArray;

// Declaration of a string array
String[] stringArray;

Initialization of Arrays:

Arrays can be initialized during declaration or later using the new keyword. There are different ways to initialize arrays in Java.

1. Using the new keyword:


// Initializing an integer array with size 5
int[] numbers = new int[5];

// Initializing a string array with size 3
String[] names = new String[3];

2. Using array literals (during declaration):


// Initializing an integer array with values
int[] scores = {90, 85, 78, 92, 88};

// Initializing a string array with values
String[] fruits = {"Apple", "Banana", "Orange"};

3. Using array literals (later, without size):


// Declaring an integer array
int[] ages;

// Initializing the integer array with values later
ages = new int[]{25, 30, 22};

4. Multi-dimensional arrays:


// Initializing a 2D array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

// Initializing a 3D array
int[][][] cube = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};

Accessing Elements of Arrays:

Array elements are accessed using their index, starting from 0.


// Accessing elements of the scores array
int firstScore = scores[0]; // 90
int secondScore = scores[1]; // 85

Array Length:

The length of an array can be obtained using the length property.


int arrayLength = scores.length; // 5

Iterating Through Arrays:

You can use loops to iterate through the elements of an array.


// Iterating through the names array
for (String fruit : fruits) {
  System.out.println(fruit);
}

Note:

Arrays in Java are zero-indexed, meaning the first element is at index 0. Ensure that the index is within the bounds of the array to avoid ArrayIndexOutOfBoundsException.