{"record":{"id":"3450b14f2faf1325","repo":"TheAlgorithms/Java","slug":"cannot-peek-from-an-empty-stack","errorCode":null,"errorMessage":"Cannot peek from an empty stack.","messagePattern":"Cannot peek from an empty stack\\.","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java","lineNumber":76,"sourceCode":"    public Item pop() {\n        if (isEmpty()) {\n            throw new IllegalStateException(\"Cannot pop from an empty stack.\");\n        }\n        Item data = head.data;\n        head = head.previous;\n        size--;\n        return data;\n    }\n\n    /**\n     * Returns the item at the top of the stack without removing it.\n     *\n     * @return the item at the top of the stack, or {@code null} if the stack is empty\n     * @throws IllegalStateException if the stack is empty\n     */\n    public Item peek() {\n        if (isEmpty()) {\n            throw new IllegalStateException(\"Cannot peek from an empty stack.\");\n        }\n        return head.data;\n    }\n\n    /**\n     * Checks whether the stack is empty.\n     *\n     * @return {@code true} if the stack has no elements, {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return head == null;\n    }\n\n    /**\n     * Returns the number of elements currently in the stack.\n     *\n     * @return the size of the stack\n     */","sourceCodeStart":58,"sourceCodeEnd":94,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java#L58-L94","documentation":"Thrown by NodeStack.peek() when the stack has no elements. peek() returns head.data without removing the node, so an empty stack would cause a NullPointerException. The IllegalStateException is a precondition violation: you are inspecting a top that does not exist.","triggerScenarios":"Calling peek() on a newly created NodeStack. Calling peek() after the stack has been drained by pops. Inspecting the top inside a loop whose exit condition is based on an external counter rather than isEmpty().","commonSituations":"Implementing algorithms (e.g., parentheses matching, monotonic-stack problems) where the first peek happens before any push. Stateful parsers that peek before pushing a sentinel. Off-by-one in loop bounds causing one extra peek.","solutions":["Check isEmpty() before each peek() call.","Seed the stack with a sentinel value so it is never empty during traversal.","Refactor the loop guard to terminate on isEmpty() rather than a separate size counter.","Catch IllegalStateException if an empty peek is an expected branch in your control flow."],"exampleFix":"// before\nItem top = stack.peek();\n// after\nItem top = stack.isEmpty() ? null : stack.peek();","handlingStrategy":"validation","validationCode":"Item top = stack.isEmpty() ? null : stack.peek();","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Guard peek() with isEmpty() when an empty stack is possible.","Seed sentinels in algorithms that must always peek.","Use isEmpty() as the loop terminator."],"tags":["stack","empty-state","java","datastructures"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}