Java: Store and Process Values in Arrays

Java Tutorial: Arrays – Store and Process Values

Java Tutorial: Arrays – Store and Process Values

This tutorial will guide you through the basics of using arrays in Java. Arrays are fundamental data structures that allow you to store a collection of elements of the same data type in a contiguous block of memory. We’ll cover declaration, initialization, accessing elements, and performing basic operations.

Example 1: Creating and Initializing a Simple Integer Array

Let’s start by creating an array to store the ages of a few people. We’ll initialize the array with some sample values.

public class ArrayExample1 {
    public static void main(String[] args) {
        // Declare an integer array named ages
        int[] ages = new int[5];

        // Assign values to the array elements
        ages[0] = 25;
        ages[1] = 30;
        ages[2] = 22;
        ages[3] = 28;
        ages[4] = 35;

        // Print the array elements
        System.out.println("Ages:");
        for (int i = 0; i < ages.length; i++) {
            System.out.println("Age " + (i + 1) + ": " + ages[i]);
        }
    }
}

Explanation:

  • We declare an integer array named `ages` using `new int[5]`. This creates an array that can hold 5 integers.
  • We assign values to the individual elements of the array using their index (starting from 0). `ages[0]` refers to the first element, `ages[1]` to the second, and so on.
  • We use a `for` loop to iterate through the array and print each element. `ages.length` provides the total number of elements in the array.

Common Mistakes:

  • IndexError: Attempting to access an array element with an index that is outside the bounds of the array (e.g., `ages[5]` when the array has only 5 elements).
  • Incorrect Loop Condition: Using a loop condition that doesn’t correctly iterate through all the elements of the array (e.g., `i <= ages.length` which would include the last element twice).

Output:

Ages:
Age 1: 25
Age 2: 30
Age 3: 22
Age 4: 28
Age 5: 35

Example 2: Creating an Array with Initialized Values

Now, let’s initialize the array directly with values instead of assigning them one by one. This is often more concise and easier to read, especially for smaller arrays.

public class ArrayExample2 {
    public static void main(String[] args) {
        // Declare and initialize an integer array
        int[] scores = {85, 92, 78, 95, 88};

        // Print the array elements
        System.out.println("Scores:");
        for (int score : scores) { // Enhanced for loop
            System.out.println(score);
        }
    }
}

Explanation:

  • We declare and initialize the `scores` array directly with values enclosed in curly braces `{}`.
  • We use an enhanced `for` loop (also known as a “for-each” loop) to iterate through the array. This loop automatically handles the indexing, making the code cleaner.

Output:

Scores:
85
92
78
95
88

Example 3: Calculating the Average of Array Elements

Let’s create a program that calculates the average of the numbers in an array. This example demonstrates how to perform calculations on the elements of an array.

public class ArrayExample3 {
    public static void main(String[] args) {
        // Declare an array of integers
        double[] numbers = {10.0, 20.0, 30.0, 40.0, 50.0};

        // Calculate the sum of the array elements
        double sum = 0;
        for (double number : numbers) {
            sum += number;
        }

        // Calculate the average
        double average = sum / numbers.length;

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

Explanation:

  • We calculate the sum of the elements by iterating through the array and adding each `number` to the `sum` variable.
  • We calculate the average by dividing the `sum` by the number of elements in the array (`numbers.length`).
  • The array is initialized with `double` values for precision.

Output:

The average is: 30.0

Leave a Reply

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

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.