Vector get(int) in Java

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

Syntax:

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

This method takes one argument. This method returns the element at the specified position in this Vector.

Parameters: One parameter is required for this method.

index: index of the element to return.

Returns: an object 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 Vectorget {
    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.get(index));
    }
}

Output:

Java


Approach 2: ArrayIndexOutOfBoundsException

Java

import java.util.Vector;

public class Vectorget {
    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.get(index));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 5 at java.base/java.util.Vector.get(Vector.java:750)



No comments:

Post a Comment