Check If Vector is Empty in Java Example

This example shows how to check if the Vector is empty in Java. This example also shows how to check if the Vector is empty using the isEmpty method and size method.

How to check if Vector is empty in Java?

There are a couple of ways using which we can check as given below.

1. Using the isEmpty method

The Vector isEmpty method returns true if this vector object does not contain any elements.

It returns false if there is at least one element in the vector object.


2. Using the size method

The Vector size method returns the number of elements contained in this vector object.

It returns 0 if there are no elements in the vector object.

We can compare the return value of the size method with 0 to check if the vector object contains any elements or not as given below.


Which method should I use to check?

Let’s have a look at the source code of the Vector class for both of these methods.

As we can see from the source code, both the methods use the same elementCount internal variable. So as far as performance is concerned, there will not be any difference between these methods.

However, using the isEmpty method makes code more readable and cleaner than getting the size and comparing it with 0 for this purpose.

This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 Vector Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping