The syntax of the isEmpty()
method is:
arraylist.isEmpty()
Here, arraylist is an object of the ArrayList
class.
isEmpty() Parameters
The isEmpty()
method does not take any parameters.
isEmpty() Return Value
- returns true if the arraylist does not contain any elements
- returns false if the arraylist contains some elements
Example: Check if ArrayList is Empty
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<String> languages = new ArrayList<>();
System.out.println("Newly Created ArrayList: " + languages);
// checks if the ArrayList has any element
boolean result = languages.isEmpty(); // true
System.out.println("Is the ArrayList empty? " + result);
// add some elements to the ArrayList
languages.add("Python");
languages.add("Java");
System.out.println("Updated ArrayList: " + languages);
// checks if the ArrayList is empty
result = languages.isEmpty(); // false
System.out.println("Is the ArrayList empty? " + result);
}
}
Output
Newly Created ArrayList: [] Is the ArrayList empty? true Updated ArrayList: [Python, Java] Is the ArrayList empty? false
In the above example, we have created a arraylist named languages. Here, we have used the isEmpty()
method to check whether the arraylist contains any elements or not.
Initially, the newly created arraylist does not contain any element. Hence, isEmpty()
returns true
. However, after adding some elements (Python, Java), the method returns false
.