List isEmpty() method in Java with Examples (original) (raw)
Last Updated : 03 Dec, 2024
The **isEmpty() method of the List interface in Java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.
**Example:
Java `
// Java Progrm to Implement // List isEmpty() Method import java.util.*;
class Main { public static void main (String[] args) { // New empty list created List l=new ArrayList<>();
// Implementing isEmpty() Method
if(l.isEmpty())
System.out.println("List is Empty");
else
System.out.println("List is not Empty");
}}
`
**Syntax of the Method
boolean isEmpty()
- **Parameter : It does not accept any parameter.
- **Return Type : It returns True if the list has no elements else it returns false. The return type is of datatype boolean.
- **Error and Exceptions : This method has no errors or exceptions.
Program Demonstrating List isEmpty() in Java
Below is the implementation of isEmpty() Method:
Java `
// Java Program Implementing // List isEmpty() Method import java.util.List; import java.util.ArrayList;
public class Main { public static void main(String[] args) {
// Creating Empty ArrayList
List<Integer> arr = new ArrayList<Integer>();
// Demonstrating isEmpty() Method
System.out.print(arr + " : ");
System.out.println(arr.isEmpty());
arr.add(1);
arr.add(2);
arr.add(3);
// Demonstrating isEmpty() Method
System.out.print(arr + " : ");
System.out.println(arr.isEmpty());
}}
`
Output
[] : true [1, 2, 3] : false
**Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#isEmpty()