Java Vector lastElement() Method with Example

In the previous article, we have discussed about Java Vector firstElement() Method with Example

In this article, we are going to see the use of Java Vector lastElement() method along with examples.

Java Vector lastElement() Method with Example

This java.util.Vector.lastElement() method can fetch the last element of a vector just by calling it. As result it returns the element present at the last index.

Syntax:

vectorName.lastElement( )

Where,

  • vectorName refers to the name of the Vector.

Approach:

  • Create an integer vector.
  • Add elements to the vector.
  • Print the elements of the vector.
  • Print the last element using the lastElement() method.

Program:

import java.util.*;
public class Main
{
   public static void main(String[] args) 
   {
       // Create a Vector of integer datatype
       Vector<Integer> vec = new Vector<Integer>();
       // Adding some elements to the vector
       vec.add(100);
       vec.add(200);
       vec.add(300);
       vec.add(400);
       vec.add(500);
       // Prints the vector elements
       System.out.println("The vector elements are "+vec);
       // Prints the last element using lastElement method
       System.out.println("The last element is "+vec.lastElement());
   }
}
Output:

The vector elements are [100, 200, 300, 400, 500]
The last element is 500

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Related Java Programs: