java.util.Vector.addElement() Method


Description

The addElement(E obj) method is used to add the specified component to the end of this vector and increasing its size by one. The capacity of this vector is increased if its size becomes greater than its capacity. This addElement() method is identical in functionality to the add(Object) method. The add() method returns true/false but the addElement() method does not return any value.

Declaration

Following is the declaration for java.util.Vector.addElement() method

public void addElement(E obj)

Parameters

obj − It refers to the component to be added.

Return Value

The return type is void

Exception

NA

Example

The following example shows the usage of java.util.Vector.addElement(E obj) method.

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {

      // create an empty Vector vec with an initial capacity of 4      
      Vector<Integer> vec = new Vector<Integer>(4);

      // use add() method to add elements in the vector
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(1);

      // let us print all the elements available in vector
      System.out.println("Initial elements in the vector :- "); 
      for (Integer number : vec) {         
         System.out.println("Number = " + number);
      }

      // add new element
      vec.addElement(12);

      // let us print all the elements again after addition
      System.out.println("Elements after addition :- "); 
      
      for (Integer number : vec) {         
         System.out.println("Number = " + number);
      }
   }    
}

Let us compile and run the above program, this will produce the following result.

Initial elements in the vector :- 
Number = 4
Number = 3
Number = 2
Number = 1
Elements after addition :- 
Number = 4
Number = 3
Number = 2
Number = 1
Number = 12
java_util_vector.htm
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements