WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Basic · question 20 of 100

How do you check if a Collection is empty in Java?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java, you can check if a Collection is empty using the isEmpty() method, which is provided by the Collection interface and implemented by all of its subinterfaces and implementing classes. The isEmpty() method returns a boolean value that indicates whether the Collection is empty (true) or not (false).

Here’s an example of how to check if a Collection is empty in Java:

import java.util.ArrayList;
import java.util.Collection;

public class Example {
    public static void main(String[] args) {
        // create an empty ArrayList of strings
        Collection<String> myCollection = new ArrayList<>();
        
        // check if the Collection is empty
        boolean isEmpty = myCollection.isEmpty();
        
        // print out whether the Collection is empty or not
        System.out.println("Is the Collection empty? " + isEmpty);
    }
}

In this example, we create an empty ArrayList of strings called "myCollection". We then use the isEmpty() method to check whether the Collection is empty and store the result in a boolean variable called "isEmpty". We use the println() method to print out whether the Collection is empty or not.

The output of this program would be:

Is the Collection empty? true

As you can see, the isEmpty() method correctly returned true because the Collection is empty.

In summary, you can check if a Collection is empty in Java using the isEmpty() method, which returns a boolean value indicating whether the Collection is empty (true) or not (false).

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics