Home » Java programming language

Java Vector lastElement() Method with Example

Vector Class lastElement() method: Here, we are going to learn about the lastElement() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 17, 2020

Vector Class lastElement() method

  • lastElement() method is available in java.util package.
  • lastElement() method is used to return the last element of this Vector.
  • lastElement() 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.
  • lastElement() method may throw an exception at the time of returning the last element.
    NoSuchElementException: This exception may throw when this Vector is "empty".

Syntax:

    public Element lastElement();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is Element, it returns the last element of this Vector.

Example:

// Java program to demonstrate the example 
// of Element lastElement() method of Vector 

import java.util.*;

public class LastElementOfVector {
    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 lastElement() method is
        // to return the last element exists 
        Object ele = v.lastElement();

        // Display Last Element
        System.out.println("v.lastElement(): " + ele);
    }
}

Output

v: [C, C++, JAVA]
v.lastElement(): JAVA



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.