Java Vector firstElement() Method with Example

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

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

Java Vector firstElement() Method with Example

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

Syntax:

vectorName.firstElement( )

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 first element using firstElement() 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 first element using firstElement() method
       System.out.println("The first element is "+vec.firstElement());
   }
}
Output:

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

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output.

Related Java Programs: