Java Vector firstElement() Example

The elementAt(int index) method of java.util.Vector class will get you the element at the specified index whereas firstElement() method will get you the element at the index ‘0’(first element).

Signature

public E firstElement() 

Retrieves the first element of the vector and will throw java.util.NoSuchElementException if the vector is empty.

Example

The following example shows the usage of java.util.Vector.firstElement() method.

import java.util.Vector;

public class FirstElementMethodVectorExample 
{
    public static void main(String args[])
    {
     // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        
        //Getting the first element of the vector
        System.out.println("First element of the Vector is : "+vector1.firstElement());
    }
}

Output

First element of the Vector is : Element1

Leave a Reply

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