Java Vector indexOf() Method

The indexOf() Java Vector class method is used to get the index of the first occurrence of the specified element in the vector. There are two different types of Java indexOf() method which can be differentiated depending on its parameter. These are:

  1. Java Vector indexOf(Object o) Method
  2. Java Vector indexOf(Object o, int index) Method

indexOf(Object o) Method:

This method is used to get the index of the first occurrence of the specified element in the vector. If the element is not found, it returns -1.

indexOf(Object o, int index> c) Method:

This method is used to get the index of the first occurrence of the specified element in the vector. It starts searching for an element in the forward direction from the specified index. If the element is not found, it returns -1.

Syntax

Following is the declaration of indexOf() method:

Parameter

ParameterDescriptionRequired/Optional
indexIt is an index where to start searching for an element in the forward direction.Required
objIt is an element to search for.Required

Return

The indexOf() method returns the index of the first occurrence of the specified element in this vector or returns -1 if the vector does not contain the element.

Exceptions

IndexOutOfBoundsException- This method has thrown an exception if the index of an array is out of range i.e. (index < 0 || index > size()).

Compatibility Version

Java 1.2 and above

Example 1

Test it Now

Output:

Index of element is: 2

Example 2

Test it Now

Output:

Index of element is: -1
The element is not found.

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2
	at java.base/java.util.Vector.indexOf(Vector.java:430)
	at myPackage.VectorIndexOfExample3.main(VectorIndexOfExample3.java:14)

Example 4

Test it Now

Output:

Index of element is found at: 3

Next TopicJava Vector




Latest Courses