TheAlgorithms/Java · error · IOException

Out of range, available %d, but trying with %d

Error message

Out of range, available %d, but trying with %d

What it means

BufferedReader.peek(n) throws IOException when n >= available() — you cannot peek beyond the bytes currently readable from the stream. The check fires before any buffer refresh, so it guards against reading past EOF. Note the boundary: it triggers on n >= available (strict), so peeking the very last available byte with n == available-1 is the maximum valid call.

Source

Thrown at src/main/java/com/thealgorithms/io/BufferedReader.java:99

        return bufferPos - posRead + available;
    }

    /**
     * Returns the next character
     */

    public int peek() throws IOException {
        return peek(1);
    }

    /**
     * Peeks and returns a value located at next {n}
     */

    public int peek(int n) throws IOException {
        int available = available();
        if (n >= available) {
            throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
        }
        pushRefreshData();

        if (n >= bufferSize) {
            throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
        }
        return buffer[n];
    }

    /**
     * Removes the already read bytes from the buffer
     * in-order to make space for new bytes to be filled up.
     * <p>
     * This may also do the job to read first time data (the whole buffer is empty)
     */

    private void pushRefreshData() throws IOException {
        for (int i = posRead, j = 0; i < bufferSize; i++, j++) {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check available() before peeking: if (reader.available() > n) reader.peek(n).
  2. Read more data first (refill) or accept that the stream is exhausted.
  3. Use peek(1) / read() loop instead of a large fixed peek near EOF.

Example fix

// before
int b = reader.peek(8); // may exceed available

// after
if (reader.available() > 8) {
    int b = reader.peek(8);
} else {
    // handle short input
}
Defensive patterns

Strategy: validation

Validate before calling

if (n >= reader.available()) {
    // not enough bytes to peek; handle short input
    return Optional.empty();
}
int b = reader.peek(n);

Prevention

When it happens

Trigger: Calling peek(n) where n >= the number of bytes available, e.g. peek(10) on a stream with only 5 bytes, or peek(0) when available() == 0 (note n==0 on empty triggers since 0 >= 0).

Common situations: Peeking ahead for a multi-byte token (e.g. a 4-byte length prefix) when the stream has fewer bytes remaining, calling peek near EOF, or passing a computed n based on expected frame size that exceeds actual data.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/4e1ba034845605c9. Report an issue: GitHub.