Get First and Last Elements from Java Vector Example

This example shows how to get the first and last elements from the Vector in Java. This example also shows how to get the first and last elements using the firstElement, lastElement, and get methods.

How to get the first and last element from the Vector in Java?

There are a couple of ways using which we can get the first element or last element from the vector object.

1. Using the firstElement and lastElement methods

The Vector firstElement method returns the first element of the vector object.

Similarly, the Vector lastElement method returns the last element of this vector object.


Important Note:

The firstElement and lastElement methods throw NoSuchElementException exception if the vector is empty. Always make sure to check if the vector is empty or not before calling any of these methods to avoid this exception.


2. Using the get method and element index

Since the Vector is an index-based data structure, we can use the Vector get method along with the index to access first and last vector elements.

The vector index starts from 0 and ends at the vector size – 1 index. So the first element of the vector object is located at index 0 while the last element is located at the vector size – 1 index.


The get method throws ArrayIndexOutOfBoundsException exception if the specified index < 0 or specified index >= vector size.


Always make sure that the vector is not empty to avoid this exception as given below.


This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 Vector Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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

Online Shopping