Javatpoint Logo
Javatpoint Logo

Java Vector add() Method

The add() is a Java Vector class method which is used to insert the specified element in the given Vector. There are two different types of Java add() method which can be differentiated depending on its parameter. These are:

  1. Java Vector add(int index, E element) Method
  2. Java Vector add(E e) Method

Java Vector add(int index, E element)

This method is used to insert the specified element at the specified position in the given Vector.

Java Vector add(E e)

This method appends the specified element to the end of this vector.

Syntax

Following is the declaration of add() method:

Parameter

Parameter Description Required/Optional
index It is the index at which the specified element is to be inserted. Required
e It is the element which will be appended to this vector. Required
element It is the element which will be inserted at the specified location. Required

Return

The add(int index, E element) method does not return anything because its return type is void.

The add(E e) method returns true if the specified element added successfully, otherwise returns false.

Exceptions

ArrayIndexOutOfBoundsException- This method has thrown an exception if the index is out of range.

Compatibility Version

Java 1.2 and above

Example 1

Test it Now

Output:

--Elements of Vector are--
Alphabet= A
Alphabet= B
Alphabet= C
Alphabet= D
Alphabet= E

Example 2

Test it Now

Output:

Vector is: [Java, Android, Python, JavaTpoint, Hindi100]

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 > 3
	at java.base/java.util.Vector.insertElementAt(Vector.java:619)
	at java.base/java.util.Vector.add(Vector.java:857)
	at myPackage.VectorAddExample3.main(VectorAddExample3.java:11)

Example 4

Test it Now

Output:

Element at index: 0 Color: White
Element at index: 1 Color: Green
Element at index: 2 Color: Black
Element at index: 3 Color: Pink
New color Yellow added at first position.
Element at index: 0 Color: White
Element at index: 1 Color: Yellow
Element at index: 2 Color: Green
Element at index: 3 Color: Black
Element at index: 4 Color: Pink

Next TopicJava Vector





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback

  • Send your Feedback to feedback@javatpoint.com

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA