ArrayList isEmpty() method in Java

The isEmpty() method is used to determine whether an ArrayList is empty or not. In this post, we will look at the isEmpty() method of the ArrayList class in detail.

  • Method declaration – public boolean isEmpty()
  • What does it do? It will check whether the Arraylist contains any elements or not.
  • What does it return? It will return true if ArrayList does not contain any elements. Otherwise, it will return false.
Code Example
public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> arraylist1 = new ArrayList<String>();
		ArrayList<String> arraylist2 = new ArrayList<String>();

		arraylist1.add("first"); // adding element to arraylist1

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

	}
}

Output –

is arraylist1 is empty? false
is arraylist2 is empty? true

Here, we can see that arraylist1 returned false because we have added an element to it, whereas arraylist2 returned false.

Internal implementation of the isEmpty() method

isEmpty() method internally checks for the size of the ArrayList, and if that size is 0, it will return true. Otherwise, it will return false.

    public boolean isEmpty() {
        return size == 0;
    }
Time Complexity of the ArrayList isEmpty() method

As shown above, the internal implementation of the isEmpty() method is just checking the size of the ArrayList. So, the time complexity of the ArrayList isEmpty() method is O(1).

The What If scenarios

Q – What if we used the isEmpty() method on a null ArrayList?

In this case, it will throw a NullPointerException, as illustrated below.

public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>();
		al = null;

		System.out.println(al.isEmpty());

	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.isEmpty()" because "al" is null
Q – What if we used the isEmpty() method on an ArrayList containing only the null objects?

In this case, it will return true as the size of the ArrayList will be increased after inserting the null objects.

public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>();
		al.add(null);
		al.add(null);

		System.out.println(al.isEmpty());

	}
}

Output –

false

Please visit this link to learn more about the ArrayList class of java and its other functions or methods.

We hope that 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.