Vector elementAt(int) in Java

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

Syntax:

String java.util.Vector.elementAt(int index)

This method takes one argument. This method returns the component at the specified index.

Parameters: One parameter is required for this method.

index: an index into this vector.

Returns: the component at the specified index.

Throws:

ArrayIndexOutOfBoundsException - if the index is out of range(index < 0 || index >= size())

Approach 1: When no exception

Java

import java.util.Vector;

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

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

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");
        int index = 1;

        System.out.println(vector.elementAt(index));
    }
}

Output:

Java


Approach 2: ArrayIndexOutOfBoundsException

Java

import java.util.Vector;

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

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

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");
        int index = 5;

        System.out.println(vector.elementAt(index));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 >= 4 at java.base/java.util.Vector.elementAt(Vector.java:466)


No comments:

Post a Comment