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 19 of 100

How do you find the size of a Collection in Java?

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

In Java, the size of a Collection can be determined using the size() method, which is provided by the Collection interface and implemented by all of its subinterfaces and implementing classes. The size() method returns the number of elements in the Collection.

Here’s an example of how to find the size of a Collection in Java:

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

public class Example {
    public static void main(String[] args) {
        // create an ArrayList of strings
        Collection<String> myCollection = new ArrayList<>();
        myCollection.add("apple");
        myCollection.add("banana");
        myCollection.add("orange");
        
        // find the size of the Collection
        int size = myCollection.size();
        
        // print out the size of the Collection
        System.out.println("Size of the Collection: " + size);
    }
}

In this example, we create an ArrayList of strings called "myCollection" and add three elements to it. We then use the size() method to find the size of the Collection and store it in an integer variable called "size". We use the println() method to print out the size of the Collection.

The output of this program would be:

Size of the Collection: 3

As you can see, the size() method correctly returned the number of elements in the Collection.

In summary, the size of a Collection in Java can be found using the size() method, which returns the number of elements in the Collection.

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