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:
- Java Vector indexOf(Object o) Method
- 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
Parameter | Description | Required/Optional |
---|---|---|
index | It is an index where to start searching for an element in the forward direction. | Required |
obj | It 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
Output:
Index of element is: 2
Example 2
Output:
Index of element is: -1 The element is not found.
Example 3
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
Output:
Index of element is found at: 3