How to calculate the average of elements in an array Java SE 22?

Calculating the average of elements in an array in Java SE 22 involves summing up all the elements in the array and dividing by the total number of elements. Here’s how you can do it:

public class Main {
public static void main(String[] args) {

// Example array
int[] array = {5, 10, 15, 20, 25};

// Calculate the sum of elements
int sum = 0;
for (int num : array) {
sum += num;
}

// Calculate the average
double average = (double) sum / array.length;

// Print the average
System.out.println("Average: " + average);
}
}

This program iterates through each element in the array, adds it to the `sum`, and then divides the `sum` by the total number of elements in the array to get the average. Make sure to handle cases where the array is empty to avoid division by zero errors.