lastElement(): This method is available in java.util.Vector class of Java.
Syntax:
K java.util.Vector.lastElement()
This method returns the last component of the vector.
Parameters: NA
Returns: the last component of the vector, i.e., the component at index size() - 1.
Throws:
NoSuchElementException - if this vector is empty
Approach 1: When no exception
Java
import java.util.Vector;public class VectorlastElement {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.lastElement());}}
Output:
Program
Approach 2: NoSuchElementException
Java
import java.util.Vector;public class VectorlastElement {public static void main(String[] args) {Vector<String> vector = new Vector<>();System.out.println(vector.lastElement());}}
Output:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Vector.lastElement(Vector.java:495)
No comments:
Post a Comment