Wednesday, September 3, 2025
HomeLanguagesJavaVector add() Method in Java

Vector add() Method in Java

boolean add(Object element): This method appends the specified element to the end of this vector. 

Syntax:

boolean add(Object element)

Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the vector. Return Value: This method returns True after successful execution, else False. Below program illustrates the working of java.util.Vector.add(Object element) method: 
Example: 

Java




// Java code to illustrate boolean add(Object element)
import java.util.*;
 
public class VectorDemo {
    public static void main(String args[])
    {
 
        // Creating an empty Vector
        Vector<String> vec_tor = new Vector<String>();
 
        // Use add() method to add elements in the vector
        vec_tor.add("Geeks");
        vec_tor.add("for");
        vec_tor.add("Geeks");
        vec_tor.add("10");
        vec_tor.add("20");
 
        // Output the present vector
        System.out.println("The vector is: " + vec_tor);
 
        // Adding new elements to the end
        vec_tor.add("Last");
        vec_tor.add("Element");
 
        // Printing the new vector
        System.out.println("The new Vector is: " + vec_tor);
    }
}


Output:

The vector is: [Geeks, for, Geeks, 10, 20]
The new Vector is: [Geeks, for, Geeks, 10, 20, Last, Element]

Time complexity: O(n). // n is the size of the vector.

Auxiliary Space: O(n).

void add(int index, Object element): This method inserts an element at a specified index in the vector. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one). 

Syntax:

void add(int index, Object element)
  • Parameters: This method accepts two parameters as described below.
    • index: The index at which the specified element is to be inserted.
    • element: The element which is needed to be inserted.
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11854 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS