Let's see an example of accessing array elements using index numbers.
Example: Access Array Elements
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
[Link]("Accessing Elements of Array:");
[Link]("First Element: " + age[0]);
[Link]("Second Element: " + age[1]);
[Link]("Third Element: " + age[2]);
[Link]("Fourth Element: " + age[3]);
[Link]("Fifth Element: " + age[4]);
Output
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
Looping Through Array Elements
In Java, we can also loop through each element of the array. For example,
Example: Using For Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
[Link]("Using for Loop:");
for(int i = 0; i < [Link]; i++) {
[Link](age[i]);
Output
Using for Loop:
12
Example: Using the for-each Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
[Link]("Using for-each Loop:");
for(int a : age) {
[Link](a);
}
}
Output
Using for-each Loop:
12
Example: Compute Sum and Average of Array Elements
class Main {
public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int sum = 0;
Double average;
// access all elements using for each loop
// add each element in sum
for (int number: numbers) {
sum += number;
// get the total number of elements
int arrayLength = [Link];
// calculate the average
// convert the average from int to double
average = ((double)sum / (double)arrayLength);
[Link]("Sum = " + sum);
[Link]("Average = " + average);
}
}
Output:
Sum = 36
Average = 3.6