Home »
Java programming language
Java Vector firstElement() Method with Example
Vector Class firstElement() method: Here, we are going to learn about the firstElement() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 17, 2020
Vector Class firstElement() method
- firstElement() method is available in java.util package.
- firstElement() method is used to retrieves the first element of this Vector.
- firstElement() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- firstElement() method may throw an exception at the time of returning the first element.
NoSuchElementException: This exception may throw when this Vector is blank.
Syntax:
public Element firstElement();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is Element, it returns the first element of this Vector.
Example:
// Java program to demonstrate the example
// of Element firstElement() method
// of Vector
import java.util.*;
public class FirstElementOfVector {
public static void main(String[] args) {
// Instantiates a Vector object with
// initial capacity of "10"
Vector < String > v = new Vector < String > (10);
// By using add() method is to add the
// elements in this v
v.add("C");
v.add("C++");
v.add("JAVA");
// Display Vector
System.out.println("v: " + v);
// By using firstElement() method is to
// return the first element exists
// in this vector v
Object ele = v.firstElement();
// Display returned element
System.out.println("v.firstElement(): " + ele);
}
}
Output
v: [C, C++, JAVA]
v.firstElement(): C