java.util
package.
package java.util;
public class Stack<E> extends Vector<E>
{
// Constructors
// Methods
// Fields
}
Stack
extends Vector
class and inherits all its methods.
Stack
is a LIFO (Last-In-First-Out) data structure where the last inserted element is the first to be removed. Stack
Class
Stack
class:
Sr. No. | Constructor | Description |
---|---|---|
1 | Stack() |
Constructs an empty Stack with an initial capacity of 10 (inherited from Vector ). |
Stack
Class
Stack
class:
Sr. No. | Method | Description |
---|---|---|
1 | E push(E item) |
Pushes (inserts) an element onto the top of the Stack and returns the element pushed. |
2 | E pop() |
Removes and returns the element at the top of the Stack. Throws EmptyStackException if the stack is empty. |
3 | E peek() |
Returns the element at the top of the Stack without removing it. |
4 | boolean empty() |
Tests whether the Stack is empty and returns true if no elements are present. |
5 | int search(Object o) |
Searches for the specified element in the Stack and returns its 1-based position from the top. Returns -1 if not found. |
Stack
extends the Vector
class and inherits all its methods and properties.
Stack
is synchronized, it is not recommended for modern applications β use Deque
(like ArrayDeque
) instead.
Stack
class from the java.util
package.
import java.util.Stack;
public class StackDemo
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<>();
// Pushing elements
stack.push("Apple");
stack.push("Banana");
stack.push("Mango");
stack.push("Banana"); // duplicate allowed
System.out.println(stack);
System.out.println("-------------------------");
// Accessing top element
System.out.println("Top Element (peek): " + stack.peek());
System.out.println("-------------------------");
// Popping element
System.out.println("Popped Element: " + stack.pop());
System.out.println(stack);
System.out.println("-------------------------");
// Searching element
System.out.println("Position of 'Apple': " + stack.search("Apple")); // top is position 1
System.out.println("-------------------------");
// Checking if stack is empty
System.out.println("Is Stack Empty? " + stack.isEmpty());
System.out.println("-------------------------");
// Iterating Stack
for(String fruit : stack)
{
System.out.println(fruit);
}
}
}
[Apple, Banana, Mango, Banana] ------------------------- Top Element (peek): Banana ------------------------- Popped Element: Banana [Apple, Banana, Mango] ------------------------- Position of 'Apple': 3 ------------------------- Is Stack Empty? false ------------------------- Apple Banana Mango
Stack
is a legacy class in Java that extends Vector
and is rarely used nowadays.Deque
or ArrayDeque
are preferred for stack implementations.Stack
Class:
index 0
.Vector
class, so it is synchronized and thread-safe.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.