Vector addElement() method in Java

In this post, we are going to look at the addElement() method implementation of the Vector class in Java.

  • Method declaration – public synchronized void addElement(E obj)
  • What does it do? – It adds the element passed in the argument at the end of the vector. It’s functionality and implementation is similar to the add() method.
  • What does it return? It doesn’t return anything back as its return type is void.
public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		// adding element into the vector
		v.addElement("first");
		v.addElement("second");

		System.out.println("Vector: " + v.toString());  // used to print the elements in the vector
	}
}

Output –

Vector: [first, second]
What will happen if we used the addElement() method on a null vector?

It will throw a NullPointerException as illustrated in the below program.

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		v = null;

		// adding element into the vector
		v.addElement("first");
		v.addElement("second");

		System.out.println("Vector: " + v.toString());
	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Vector.addElement(Object)" because "v" is null
What if we tried to add the null object ?

It will successfully add the null object as if it would have been a normal object.

public class Codekru {

	public static void main(String[] args) {

		Vector<String> v = new Vector<String>();

		// adding element into the vector
		v.addElement(null);
		v.addElement("second");

		System.out.println("Vector: " + v.toString());
	}
}

Output –

Vector: [null, second]

add vs addElement

You might be wondering that if the addElement() method does essentially the same thing as that of add() method and even have same implementations behind the scene, then why would we need two methods performing the same thing at all?
Well, there is not much difference between them, apart from that the add() method is a part of the Collection interface and as Vector class indirectly implements the Collection interface, then it has to implement the add method whereas the addElement() method is the legacy method that was already there with the Vector class and thus we ended up with the two methods doing the same thing.

Please visit this link if you want to know more about the Vector class in java and its other functions or methods.

Hope you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.