# Get first and last elements from Vector in Java

Java 8Object Oriented ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

The first element in the Vector can be obtained using the java.util.Vector.firstElement() method. The last element in the Vector can be obtained using the java.util.Vector.lastElement() method. Neither of these methods requires any parameters.

A program that demonstrates this is given as follows:

## Example

Live Demo

import java.util.Vector;
public class Demo {
public static void main(String args[]) {
Vector vec = new Vector();
System.out.println("The Vector elements are: " + vec);
System.out.println("The first element of the Vector is : " + vec.firstElement());
System.out.println("The last element of the Vector is : " + vec.lastElement());
}
}

The output of the above program is as follows:

The Vector elements are: [4, 7, 2, 8, 6]
The first element of the Vector is : 4
The last element of the Vector is : 6

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. Vector.firstElement() and Vector.lastElement() are used to get the first and last elements of the Vector respectively. These elements are displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector();
System.out.println("The last element of the Vector is : " + vec.lastElement());