Java size()
Anonymous contributor
Published Oct 30, 2025
Contribute to Docs
In Java, size() method returns the number of elements currently present in a collection like a queue, helping determine how many items are stored at any given moment.
Syntax
queue.size()
Parameters:
The size() method does not take any parameters.
Return value:
- Returns an integer representing the number of elements in the queue.
Example 1: Get Queue Length using Java size()
In this example, the size() method in Java is used to find the number of elements present in a queue:
import java.util.LinkedList;import java.util.Queue;public class QueueSizeExample {public static void main(String[] args) {Queue<String> queue = new LinkedList<>();queue.add("Apple");queue.add("Banana");queue.add("Cherry");System.out.println("Queue size: " + queue.size());}}
The output of this code is:
Queue size: 3
Example 2: Check Queue Size Before Processing
In this example, the size() method in Java is used to verify if a queue contains elements before processing them:
import java.util.LinkedList;import java.util.Queue;public class QueueSizeCheckExample {public static void main(String[] args) {Queue<Integer> numbers = new LinkedList<>();numbers.add(10);numbers.add(20);numbers.add(30);if (numbers.size() > 0) {System.out.println("Queue has " + numbers.size() + " elements. Processing...");while (!numbers.isEmpty()) {System.out.println("Removed: " + numbers.remove());}} else {System.out.println("Queue is empty. Nothing to process.");}}}
The output of this code is:
Queue has 3 elements. Processing...Removed: 10Removed: 20Removed: 30
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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