Java Vector elementAt() Method with Example

In the previous article, we have discussed about Java Vector removeElementAt() Method with Examples

In this article, we are going to see display element at a particular index using elementAt( ) method by using Java programming language.

Java Vector elementAt() Method with Example

This java.util.Vector.elementAt() method can fetch the element at any specified index just by passing the index to it. It returns the element present at that index. If the index greater than vector it invokes the array out of bounds exception.

Syntax:

 vectoreName.elementAt(int index_of_element)

Where,

  • vectorName refers to the name of the Vector.
  • int index_of_element refers to the location from which we want to fetch the element.

Approach:

  • Create an integer vector.
  • Add elements to the vector.
  • Print the elements of the vector.
  • Print the element at a particular index using elementAt( ) method.

Program:

import java.util.*;
public class Main
{
   public static void main(String[] args)
   {
       // Create a Vector of integer datatype
       Vector<Integer> vec = new Vector<Integer>();
       // Adding some elements to the vector
       vec.add(100);
       vec.add(200);
       vec.add(300);
       vec.add(400);
       vec.add(500);
       // Prints the vector elements
       System.out.println("The vector elements are "+vec);
       // Print the element at a particular index using elementAt( ) method
       System.out.println("The second element is "+vec.elementAt(1));
   }
}
Output:

The vector elements are [100, 200, 300, 400, 500]
The second element is 200

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Related Java Programs: