Vector isEmpty() method in Java

The isEmpty() method helps us in finding out whether a vector is empty or not. In this post, we are going to discuss the isEmpty() method of the vector class in detail.

  • Method declaration – public synchronized boolean isEmpty()
  • What does it do? – It tells us whether the vector is empty or not by checking the elementCount or we can say the size of the vector
  • What does it return? – It will return true if the vector is empty otherwise false
The internal implementation of the isEmpty() method
 public synchronized boolean isEmpty() {
        return elementCount == 0;
 }

Here we can see that the elementCount is used to check whether a vector is empty or not.

Code example
public class Codekru {

	public static void main(String[] args) {

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

		System.out.println("is v1 empty? " + v1.isEmpty());

		// adding elements
		v1.add("first");
		v1.add("second");

		System.out.println("is v1 empty now? " + v1.isEmpty());
	}
}

Output –

is v1 empty? true
is v1 empty now? false

The What If scenarios

What if we try to use the isEmpty() method on a vector that contains empty strings only?

In this case, even if we are adding an empty string, it is treated as an element and thus the elementCount will be increased by 1. So, the isEmpty() method would return false as it checks whether the elementCount is equal to 0 or not.

public class Codekru {

	public static void main(String[] args) {

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

		v.add(""); // adding an empty string

		System.out.println("is v1 empty? " + v.isEmpty());
	}
}

Output –

is v1 empty? false
What if we try to use the isEmpty() method on a vector that contains null objects only?

Again here, a null object is nevertheless an object. So, the elementCount will again be increased by 1, and the isEmpty() method would return false.

public class Codekru {

	public static void main(String[] args) {

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

		v.add(null); // adding a null object

		System.out.println("is v1 empty? " + v.isEmpty());
	}
}

Output –

is v1 empty? false
Now, what if we use the isEmpty() method on a null vector?

Here, we will get a NullPointerException as illustrated by the below program.

public class Codekru {

	public static void main(String[] args) {

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

		v = null;

		System.out.println("is v1 empty? " + v.isEmpty());
	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Vector.isEmpty()" because "v" is null

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. Required fields are marked *