Core Java

Last Element Test in Java Array

When working with arrays in Java, there are situations where you may need to check if an element is the last one in the array while iterating over it. This is particularly useful for formatting outputs, adding specific behaviors for the last element, or even in custom iteration logic. Let us delve into understanding the Java array last element test and explore different ways to check if an element is the last one while iterating over an array.

1. Checking the Indexes in Loops

The most straightforward way to check if you are at the last element is by comparing the current index to the length of the array minus one. This works well when using a for loop with index-based iteration. Let’s take a look at the below code:

public class LastElementCheck {
  public static void main(String[] args) {
    String[] items = {"apple", "banana", "orange"};

    for (int i = 0; i < items.length; i++) {
      if (i == items.length - 1) {
        System.out.println(items[i] + " (last element)");
      } else {
        System.out.println(items[i]);
      }
    }
  }
}

1.1 Code Explanation and Output

The code defines a:

  • i == items.length - 1: This condition checks if the current index is the last one.
  • The loop runs from 0 to items.length - 1, ensuring all elements are iterated over.

When we run the above code, the following output will be shown on the IDE console:

apple
banana
orange (last element)

2. Using For-Each Loop with an External Counter

In a for-each loop, there’s no direct access to the index. However, you can maintain an external counter to track the position in the array. Let’s take a look at the below code:

public class LastElementCheck {
  public static void main(String[] args) {
    String[] items = {"apple", "banana", "orange"};
    int index = 0;

    for (String item : items) {
      if (index == items.length - 1) {
        System.out.println(item + " (last element)");
      } else {
        System.out.println(item);
      }
      index++;
    }
  }
}

2.1 Code Explanation and Output

The code defines a:

  • We manually maintain an index variable that increments in each iteration of the loop.
  • We compare the index to items.length - 1 to identify the last element.

When we run the above code, the following output will be shown on the IDE console:

apple
banana
orange (last element)

3. Converting the Array to an Iterable

You can convert the array into a more flexible structure like a List or use Java’s built-in utility classes. This allows you to leverage the List API for more advanced operations, including checking if an element is the last one. Let’s take a look at the below code:

import java.util.Arrays;
import java.util.List;

public class LastElementCheck {
  public static void main(String[] args) {
    List<String> items = Arrays.asList("apple", "banana", "orange");

    for (String item : items) {
      if (item.equals(items.get(items.size() - 1))) {
        System.out.println(item + " (last element)");
      } else {
        System.out.println(item);
      }
    }
  }
}

3.1 Code Explanation and Output

The code defines a:

  • The array is converted to a List using Arrays.asList().
  • We compare the current item to the last element using items.get(items.size() - 1).

When we run the above code, the following output will be shown on the IDE console:

apple
banana
orange (last element)

4. Creating a Custom Iterator

If you need more control over iteration, you can create a custom iterator. This approach allows you to track the state of the current element and check if it’s the last one. Let’s take a look at the below code:

import java.util.Iterator;

public class LastElementCheck {
  public static void main(String[] args) {
    String[] items = {"apple", "banana", "orange"};
    CustomIterator iterator = new CustomIterator(items);

    while (iterator.hasNext()) {
      String item = iterator.next();
      if (!iterator.hasNext()) {
        System.out.println(item + " (last element)");
      } else {
        System.out.println(item);
      }
    }
  }
}

class CustomIterator implements Iterator<String> {
  private String[] items;
  private int index;

  public CustomIterator(String[] items) {
    this.items = items;
    this.index = 0;
  }

  @Override
  public boolean hasNext() {
    return index < items.length;
  }

  @Override
  public String next() {
    return items[index++];
  }
}

4.1 Code Explanation and Output

The code defines a:

  • CustomIterator implements Iterator and overrides the hasNext() and next() methods.
  • In the loop, we check if hasNext() is false after retrieving the next item to determine if it’s the last element.

When we run the above code, the following output will be shown on the IDE console:

apple
banana
orange (last element)

5. Conclusion

In Java, there are multiple ways to check if an element is the last element while iterating over an array. From index-based loops to custom iterators, each approach has its advantages based on the use case. The most straightforward method is index comparison, but you may prefer other methods when using for-each loops or needing advanced iteration control. By understanding these techniques, you can choose the most appropriate solution for your specific problem when working with arrays in Java.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
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