Home » Java programming language

Java Vector add() Method with Example

Vector Class add() method: Here, we are going to learn about the add() method of Vector Class with its syntax and example.
Submitted by Preeti Jain, on March 15, 2020

Vector Class add() method

Syntax:

    public boolean add(Element ele);
    public boolean add(int indices, Element ele);
  • add() method is available in java.util package.
  • add(Element ele) method is used to add the given element (ele) at the last of this vector.
  • add(int indices, Element ele) method is used to add the given element at the given indices.
  • These methods may throw an exception at the time of adding an element.
    IndexOutOfBoundsException: This exception may throw when the given parameter is not in a range.
  • These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.

Parameter(s):

  • In the first case, add(Element ele),
    Element ele – represents the element is to be inserted in this vector.
  • In the first case, add(int indices, Element ele),
    • int indices – represents the position of inserted element.
    • Element ele – represents the element is to be inserted in this vector.

Return value:

In the first case, the return type of the method is boolean, it returns true when the given element is to be added successfully otherwise it returns false.

In the second case, the return type of the method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of add() method of Vector

import java.util.*;

public class AddOfVector {
    public static void main(String[] args) {
        // Instantiates a vector object     
        Vector < String > v = new Vector < String > (10);

        // By using add() method is to add
        // the elements in vector
        v.add("C");
        v.add("C++");
        v.add("SFDC");
        v.add("JAVA");

        //Display Vector
        System.out.println("v: " + v);

        // By using add(object) method is used
        // to add the given object at the last
        // of this Vector
        v.add("PHP");

        // Display Vector
        System.out.println("v.add(PHP): " + v);

        // By using add(object,indices) method is used
        // to add the given object at the given indices
        // of this Vector
        v.add(2, "COBOL");

        //Display Vector
        System.out.println("v.add(2,COBOL): " + v);
    }
}

Output

v: [C, C++, SFDC, JAVA]
v.add(PHP): [C, C++, SFDC, JAVA, PHP]
v.add(2,COBOL): [C, C++, COBOL, SFDC, JAVA, PHP]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.