Library contents

Java NoSuchElementException

Removing the first element from an empty deque throws NoSuchElementException. pollFirst can represent an empty queue with null.

A simple example

NoSuchElementException

  1. Start with Queue containing no items
  2. Do this Request the first item
  3. Result No item available
Check for an empty result or handle the empty-queue failure before using a value.

Syntax

Java syntax
queue.removeFirst()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Call the next person at the clinic

A receptionist calls patients from the morning queue. If the final patient has already checked in, the screen should display an empty-queue message instead of trying to issue another number.

ResultNo patients waiting
Main.java
import java.util.ArrayDeque;
import java.util.NoSuchElementException;

class Main {
    public static void main(String[] args) throws Exception {
        var patients = new ArrayDeque<String>();
        try {
            System.out.println(patients.removeFirst());
        } catch (NoSuchElementException empty) {
            System.out.println("No patients waiting");
        }
    }
}
Output
No patients waiting

The queue contains zero patients. The receptionist can keep the window open without inventing a ticket.

Advertisements

Check for walk-ins without throwing

A clinic checks the walk-in queue between appointments. The receptionist needs a clear idle status during quiet hours and a patient number when someone arrives.

ResultDesk available
Main.java
import java.util.ArrayDeque;

class Main {
    public static void main(String[] args) throws Exception {
        var walkIns = new ArrayDeque<Integer>();
        Integer ticket = walkIns.pollFirst();
        System.out.println(ticket == null ? "Desk available" : ticket);
    }
}
Output
Desk available

pollFirst returns null on this empty ArrayDeque, so a quiet shift is a normal branch.

Call a waiting pupil

The music desk has one pupil in its equipment queue. Take the next name from the queue. An empty queue should send the desk back to waiting.

GivenQueue [Mila]
Worked resultVisitor ready
Code and output in Java
Java source
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;

class Main {
    public static void main(String[] args) throws Exception {
        try {
            new ArrayDeque<>(List.of("Mila")).removeFirst();
            System.out.println("Visitor ready");
        } catch (NoSuchElementException problem) {
            System.out.println("Wait for next visitor");
        }
    }
}
Output
Visitor ready

What to watch for

Choose the removal method according to whether an empty queue is expected. ArrayDeque prohibits null elements.

Documentation for NoSuchElementException