Core Java

Finding the Middle Element of an Array in Java

Arrays are fundamental data structures in Java that allow us to organize and store multiple elements of the same data type in a single variable. Sometimes, we may find ourselves needing to access or manipulate the middle item of an array which could be odd or even-sized. This article will delve into various approaches for finding and working with the middle item in Java arrays.

1. Understanding Java Arrays

Before we get into the details of the middle element of an Array, it’s important to understand the basics of Java arrays. Understanding how to work with arrays is essential for manipulating specific elements, such as the middle item. An array is a data structure that stores elements of the same data type in a contiguous block of memory. It provides a way to group variables under a single name.

Each element in the array can be accessed using an index, with the indexing starting from 0 for the first element. The array’s length is predetermined upon creation, and elements are accessed through square brackets [].

// Example: Declaring and initializing an array of integers
int[] numbers = {1, 2, 3, 4, 5};

2. Understanding the Middle Element

Before we get into the Java code, let’s establish a clear understanding of what the middle element of an array means.

In an array with an odd number of elements, the middle element is the one that divides the array into two equal halves. For instance, suppose we have an initial array of int[] numbers = {1,2,3,4,5}, After the execution of the array operation to identify the middle element within the array, the result will be 3.

In an array with an even number of elements, there isn’t a single middle element, but rather two middle elements. Suppose there is an original array of int[] numbers = {1, 3, 5, 7, 9, 8} , After performing the array operation to identify the elements which is the middle element of the array, the result will be 5 and 7.

3. Locating the Middle Item in Odd-Length Arrays

When an array has an odd length, finding the middle item is straightforward. The middle index can be calculated using the formula (length - 1) / 2. Let’s explore an example to illustrate this:


public class MiddleElementFinder {
    

    public static void main(String[] args) {

        int[] oddArray = {1, 2, 9, 8, 5, 6, 7};
        
        int middleIndex = (oddArray.length - 1) / 2;
        
        int middleItem = oddArray[middleIndex];
        
        System.out.println("Middle item in odd-length array: " + middleItem);
        
        
    }
}

In the example above,

  • An array named oddArray is declared and initialized. The array contains 7 integers.
  • The variable middleIndex is then calculated. This variable represents the index of the middle item in the array. The formula (array.length - 1) / 2 is used to find the middle index. In this case, the length of oddArray is 7, so the calculation is (7 - 1) / 2, resulting in 3. Therefore, middleIndex is assigned the value 3.
  • The middle item is then retrieved from the oddArray using the calculated middleIndex. In Java, array indices start from 0, so accessing oddArray[3] corresponds to retrieving the item at the fourth position in the array. In this specific array, the middle item is 8, which is at index 3.

When we run this code, the output will be:

Fig 1: Odd-length Java array middle item
Fig 1: Odd-length Java array middle item

4. Locating the Middle Item in Even-Length Arrays

Arrays that have an even number of elements pose a special situation because there is no one middle item. Instead, there are two items in the middle, forming a pair. The approach depends on specific requirements, with developers typically choosing either the left or right middle item. Let’s consider an example:


public class MiddleElementFinder {

    public static void main(String[] args) {

        int[] evenArray = {1, 2, 3, 4, 5, 6};

        int middleIndex = evenArray.length / 2 - 1;
        
        int middleIndex2 = evenArray.length / 2;

        int middleItem = evenArray[middleIndex];
        
        int middleItem2 = evenArray[middleIndex2];
 
        System.out.println("Left middle item in even-length array: " + middleItem);
        System.out.println("Right middle item in even-length array: " + middleItem2);

    }
}

Let’s go through the provided Java code:

  • We begin with an array named evenArray which is declared and initialized. The array contains six integers.
  • The variable middleIndex is calculated. This variable represents the index of the left middle item in the array. The formula array.length / 2 - 1 is used to find this index. In this case, the length of evenArray is 6, so the calculation is 6 / 2 - 1, resulting in 2. Therefore, middleIndex is assigned the value 2.
  • The variable middleIndex2 is calculated using a similar formula, representing the index of the right middle item in the array. The calculation is 6 / 2, resulting in 3. Therefore, middleIndex2 is assigned the value 3.
  • int middleItem = evenArray[middleIndex]; int middleItem2 = evenArray[middleIndex2]; represents the left middle item (middleItem) and the right middle item (middleItem2) that are then retrieved from the evenArray using the calculated indices.

When we run this code, the output will be:

Left middle item in even-length array: 3
Right middle item in even-length array: 4

4. Addressing Special Cases

When working with arrays, it’s essential to consider edge cases. Consider the scenario of an empty array, which has no middle item. To address this, a conditional check is added to ensure the array is not empty before attempting to access the middle item. For example:

public class MiddleElementFinder {

    public static void main(String[] args) {

        int[] array = {};
        if (array.length > 0) {
            if (array.length % 2 == 0) {
                System.out.println("The middle elements are: ");
                // even-length array 
                int x = array[(array.length / 2) - 1];
                System.out.println(x);
                int y = array[array.length / 2];
                System.out.println(y);
            }
            if (array.length % 2 == 1) {
                // Odd-sized array
                System.out.println("The Middle element is " + array[(array.length - 1) / 2]);
            }
        } else {
            System.out.println("The array is empty.");
        }
    }
}

This code snippet uses an if-else statement to check whether the length of the array is greater than 0. The length property of an array in Java gives the number of elements it contains.

In this case, since array is indeed empty (with a length of 0), the condition array.length > 0 evaluates to false. As a result, the code inside the else block is executed.

5. Using Java Streams for Odd and Even-sized Arrays

Java 8 introduced the Stream API which provides a simpler and more expressive method for doing things with collections of data. Let’s explore examples of using the Stream API to find the middle element for both odd and even-sized arrays.

5.1 Find Middle Element in an Odd-sized Array Using Java Streams

Let’s explore some Java code that takes an array of integers as input and returns the middle element of the array. It assumes that the array has an odd number of elements. If the array is empty, it throws an IllegalArgumentException.


public class MiddleElementUsingStreams {

    public static int findMiddleOdd(int[] array) {
        return Arrays.stream(array)
                .skip(array.length / 2)
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Array is empty"));
    }

    public static void main(String[] args) {
        int[] oddArray = {1, 2, 3, 9, 5};
        int middleElement = findMiddleOdd(oddArray);
        System.out.println("Middle Element in Odd-sized Array: " + middleElement);
    }
    
}

Here is an explanation of the above code:

  • The findMiddleOdd method uses the Arrays.stream method to convert the input array into a stream of integers.
  • The skip method is then used to skip the first half of the elements in the stream. This effectively moves to the middle element of the array.
  • The findFirst method is used to retrieve the first element in the remaining stream, which is the middle element of the original array.
  • The orElseThrow method is used to provide a default value (throwing an exception with a specified message) in case the array is empty.
  • In the main method, we define an array named oddArray, and the findMiddleOdd method is called with this array. The result is then printed to the console.

When we run the above code, the output will be:

Middle Element in Odd-sized Array: 3

Note: This code assumes that the input array always has an odd number of elements. If the array has an even number of elements, the behavior will not be as expected.

5.2 Find Middle Elements in an Even-sized Array Using Java Streams

Let’s take a look at a Java program that takes an array of integers as input and returns an array containing the two middle elements of the input array. It assumes that the input array has an even number of elements.

public class MiddleElementsUsingStreamsEven {

    public static int[] findMiddleBothEven(int[] array) {
        int middleIndex1 = array.length / 2 - 1; // Calculate the index of the first middle element
        int middleIndex2 = array.length / 2;   // Calculate the index of the second middle element

        return Arrays.stream(array) // Convert the array to a stream of integers
                .skip(middleIndex1) // Skip the first middle element
                .limit(2) // Limit the stream to the next two elements
                .toArray();         // Convert the stream to an array
    }

    public static void main(String[] args) {
        int[] evenArray = {1, 4, 2, 5, 3, 6}; // Example array with even length
        int[] middleElements = findMiddleBothEven(evenArray);  // Call the findMiddleBothEven method

        System.out.println("Middle Elements in Even-sized Array: " + Arrays.toString(middleElements)); // Print the result
    }

}


  • The findMiddleBothEven method begins by calculating two middle indices (middleIndex1 and middleIndex2) based on the length of the input array. These indices correspond to the two middle elements in an even-sized array.
  • It then uses the Arrays.stream method to convert the input array into a stream of integers.
  • The skip method is used to skip the first middle element in the stream (indexed by middleIndex1).
  • The limit(2) method limits the stream to the next two elements, which are the two middle elements of the original array.
  • The toArray method is used to convert the stream to an array, and this array is then returned by the method.
  • In the main method, we define an array named evenArray, and the findMiddleBothEven method is called with this array.

When we run this code, the output will be:

Middle Elements in Even-sized Array: [2, 5]

6. Conclusion

In this article, we explored various methods for identifying the middle elements of an array in Java. Accessing the middle item in Java arrays involves a straightforward calculation based on the array’s length. Whether the array has an odd or even length dictates the specific index calculation.

Also, we can use Java Streams to discover the middle element of an array. This approach offers a simple and clear solution. It makes the code easy to read and maintain by allowing us to express complex operations straightforwardly.

7. Download the Source Code

This was an example of Finding the Middle Element of an Array in Java.

Download
You can download the full source code of this example here: Finding the Middle Element of an Array in Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button