Java program for Vector.addElement() Method

JAVA program for Vector.addElement() Method

This JAVA program is to demonstrate the use of Vector.addElement() method.

The addElement() method inserts an element in the Vector. We can also use add() method, if you want to use add() method just replace addElement() with add() method.

We will be inserting elements by taking user input. We have additionally used the size() method as it gives us the length as well as the elementAt() method which returns the element at the specified index.

Program

import java.util.*;

class v2
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int i,n;
		Vector<Integer> v = new Vector<Integer>();				
		System.out.println("how many elements do you want to insert?");
		n=sc.nextInt();
		
		System.out.println("Start inserting the elements");
		for(i=0;i<n;i++)
		{
			v.addElement(sc.nextInt());		
		}
		
		System.out.println("Elements Inserted are:-");
		for(i=0;i<v.size();i++)
		{
			System.out.print(v.elementAt(i)+" ");	
		}	
		/*for(Integer no : v)  //Another way of printing
			System.out.println(no);*/
	}
}

Output

Share Me!