Vector firstElement() in Java

firstElement(): This method is available in java.util.Vector class of Java.

Syntax:

String java.util.Vector.firstElement()

This method returns the first component (the item at index 0) of this vector.

Parameters: NA

Returns: the first component of this vector.

Throws:

NoSuchElementException - if this vector has no components

Approach 1: When no exception

Java

import java.util.Vector;

public class VectorfirstElement {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        System.out.println(vector.firstElement());
    }
}

Output:

Hello


Approach 2: NoSuchElementException

Java

import java.util.Vector;

public class VectorfirstElement {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        System.out.println(vector.firstElement());
    }
}

Output:

Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Vector.firstElement(Vector.java:481)


No comments:

Post a Comment