Stack in Java
In Java, a stack is a collection of elements that can be accessed using a last-in-first-out (LIFO) approach. This means that the most recently added element is the first one to be removed. The stack is a subclass of the Vector class, which means that it is implemented using an array.
Here is an example of how to use a stack in Java:
javaimport java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
// push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
// pop elements from the stack
int poppedElement = stack.pop(); // 30
System.out.println("Popped element: " + poppedElement);
// peek at the top element without removing it
int topElement = stack.peek(); // 20
System.out.println("Top element: " + topElement);
// check if the stack is empty
boolean isEmpty = stack.empty(); // false
System.out.println("Is stack empty? " + isEmpty);
}
}
In this example, we create a stack of integers and add three elements to it using the push
method. We then remove the top element using the pop
method and print it. We also peek at the top element using the peek
method without removing it and print it. Finally, we check if the stack is empty using the empty
method and print the result.
Comments
Post a Comment