Understanding Arrays in Java

What is an Array?

An array is a collection of similar data types stored in contiguous memory locations. It’s a fundamental data structure in programming that allows you to store and manipulate multiple values of the same type.

Declaring an Array in Java

To declare an array in Java, you need to specify the data type and the name of the array. The syntax is as follows:

java
dataType[] arrayName;

For example:

java
double[] data;

This declares an array named data that can hold values of type double.

Initializing Arrays in Java

You can initialize an array in Java during declaration or later using the index number. Here’s an example:

java
int[] age = {10, 20, 30, 40, 50};

This initializes an array named age with five elements.

Accessing Elements of an Array in Java

You can access elements of an array using the index number. The syntax is as follows:

java
arrayName[index];

For example:

java
int[] age = {10, 20, 30, 40, 50};
System.out.println(age[0]); // prints 10

Looping Through Array Elements

You can loop through each element of an array using a for loop or a for-each loop. Here’s an example:

java
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

Multidimensional Arrays

A multidimensional array is an array of arrays. You can declare a multidimensional array in Java by specifying the number of dimensions. Here’s an example:

java
int[][] matrix = {{1, 2}, {3, 4}};

This declares a 2-dimensional array named matrix.

Example: Compute Sum and Average of Array Elements

Here’s an example that computes the sum and average of an array:

java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);

This code computes the sum and average of the numbers array and prints the result.

Leave a Reply

Your email address will not be published. Required fields are marked *