CodeToConcept
About

java

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

Sample Question

Think it through, then check the tutorial.

CodeToConcept

Quickly learn through simple, structured, and practical coding tutorials. Build your confidence from step zero to real-world experience.

© 2026 CodeToConcept. All rights reserved.

Quick Links

AboutTutorials

Tutorials

JavaHTMLCSS

Support

Privacy PolicyTerms of ServiceContact
GitHubTwitterYouTube

Java Stack

Stack is a legacy Java collection class used to implement a Last In, First Out (LIFO) data structure.

LIFO means that the element added most recently is removed first.

A simple real-world example is a stack of plates:

    ┌─────────┐
     │ Plate 3 │ ← Added last / removed first
     ├─────────┤
     │ Plate 2 │
     ├─────────┤
     │ Plate 1 │ ← Added first
     └─────────┘

In Java:

Stack<String> stack = new Stack<>();
 
stack.push("A");
stack.push("B");
stack.push("C");
 
System.out.println(stack);

Output

[A, B, C]

The top element is C.

Why Use a Stack?

A stack is useful when the most recently added item needs to be processed first.

Common examples include:

  • Undo operations
  • Backtracking
  • Expression processing
  • Navigation history
  • Depth-first traversal
  • Temporary processing of nested operations

Creating a Stack

Import the class:

import java.util.Stack;

Create an object:

Stack<String> stack = new Stack<>();

Adding Elements Using push()

The push() method adds an element to the top of the stack.

stack.push("Java");
stack.push("Python");
stack.push("C++");

The stack becomes:

C++
Python
Java

C++ is the top element.

Removing Elements Using pop()

The pop() method removes and returns the element at the top.

String language = stack.pop();
 
System.out.println(language);

Output

C++

The remaining stack is:

Python
Java

Reading the Top Element Using peek()

peek() returns the top element without removing it.

String top = stack.peek();
 
System.out.println(top);

If the stack contains:

C++
Python
Java

peek() returns:

C++

The stack remains unchanged.

Checking Whether the Stack Is Empty

Use:

stack.empty();

Example

if (stack.empty()) {
    System.out.println("Stack is empty");
}

isEmpty() can also be used because Stack inherits collection methods.

stack.isEmpty();

Searching the Stack

search() returns the position of an element measured from the top of the stack.

Stack<String> stack = new Stack<>();
 
stack.push("A");
stack.push("B");
stack.push("C");
 
System.out.println(stack.search("C"));
System.out.println(stack.search("A"));

Output

1
3

Because C is at the top, its position is 1.

Stack Follows LIFO

Consider:

Stack<Integer> stack = new Stack<>();
 
stack.push(10);
stack.push(20);
stack.push(30);

The stack is:

30 ← Top
20
10

Now:

System.out.println(stack.pop());

Output

30

Then:

System.out.println(stack.pop());

Output

20

Then:

System.out.println(stack.pop());

Output

10

So the order is:

10 → 20 → 30

Removal:

30 → 20 → 10

Complete Example

import java.util.Stack;
 
public class HelloWorld {
    public static void main(String[] args) {
 
        Stack<String> stack = new Stack<>();
 
        stack.push("Java");
        stack.push("Python");
        stack.push("C++");
 
        System.out.println("Stack: " + stack);
 
        System.out.println("Top: " + stack.peek());
 
        System.out.println("Removed: " + stack.pop());
 
        System.out.println("Stack after pop: " + stack);
    }
}

Output

Stack: [Java, Python, C++]
Top: C++
Removed: C++
Stack after pop: [Java, Python]

Stack and Deque

Although Java provides Stack, modern Java code often uses Deque when stack behavior is required.

For example:

Deque<String> stack = new ArrayDeque<>();
 
stack.push("A");
stack.push("B");
stack.push("C");
 
System.out.println(stack.pop());

Output

C

This provides stack behavior without using the legacy Stack class.

Stack vs Queue

FeatureStackQueue
PrincipleLIFOFIFO is common; implementation dependent
First processedLast addedFirst added for FIFO queues
Add operationpush()offer()
Remove operationpop()poll()
Read next elementpeek()peek()
ExampleUndo historyCustomer waiting line

Stack vs ArrayDeque

FeatureStackArrayDeque
PurposeStackQueue/Deque/Stack
Legacy classYesNo
Stack operationsYesYes
Typical modern choice for stack behaviorLess commonCommon
Null elementsPermittedNot permitted

What Happens When pop() Is Called on an Empty Stack?

Calling:

stack.pop();

when the stack is empty causes:

EmptyStackException

Therefore, you can check first:

if (!stack.empty()) {
    System.out.println(stack.pop());
}

Important Points

  • Stack follows the LIFO principle.
  • push() adds an element.

pop() removes the top element. peek() reads the top element without removing it. empty() checks whether the stack contains elements. search() searches from the top of the stack. Stack extends Vector. Stack is a legacy collection class. For new code, Deque with ArrayDeque is generally preferred for stack behavior.

Key Takeaway

A stack is a Last In, First Out (LIFO) data structure. Java's Stack class provides operations such as push(), pop(), and peek(). Although Stack is still available and commonly encountered in existing code, Deque with ArrayDeque is generally the preferred approach when implementing a stack in modern Java.

See you in next page....🙂

← VectorOverview →
← VectorOverview →