Java .isEmpty()

andersooi's avatar
Published Mar 10, 2024
Contribute to Docs

The .isEmpty() function checks if a given ArrayList is empty. It returns true if the ArrayList is empty and false if it is not empty.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

myArrayList.isEmpty();
  • myArrayList: The name of the ArrayList on which the .isEmpty() function is called.

Example

The following example demonstrates how to call the .isEmpty() function on an ArrayList named fruits:

import java.util.ArrayList;
public class Fruits {
public static void main(String[] args) {
// Creating a new ArrayList
ArrayList<String> fruits = new ArrayList<String>();
// Using the .isEmpty() function
System.out.println("Is fruits empty: " + fruits.isEmpty());
fruits.add("kiwi");
fruits.add("pineapple");
fruits.add("mango");
System.out.println("Is fruits empty: " + fruits.isEmpty());
}
}

The above example will give the following output:

Is fruits empty: true
Is fruits empty: false

Above, the .isEmpty() function returns true in the first case because fruits was initially empty. Then, in the second case, it returns false as it is called after the three fruits are added to fruits.

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours