Stack
The Stack
class in Java represents a Last-In-First-Out (LIFO) data structure, where the last element added to the stack is the first one to be removed. It provides methods to push elements onto the stack, pop elements from the stack, get the top element without removing it, check if the stack is empty, and get the size of the stack.
To use the Stack class, you need to import the java.util.Stack
package.
Here's an example that demonstrates the usage of the Stack class:
TEXT/X-JAVA
1import java.util.Stack;
2
3public class Main {
4
5 public static void main(String[] args) {
6 // Create a stack
7 Stack<Integer> stack = new Stack<>();
8
9 // Push elements onto the stack
10 stack.push(5);
11 stack.push(10);
12 stack.push(15);
13
14 // Pop an element from the stack
15 int element = stack.pop();
16 System.out.println("Popped element: " + element);
17
18 // Get the top element of the stack without removing
19 int top = stack.peek();
20 System.out.println("Top element: " + top);
21
22 // Check if the stack is empty
23 boolean isEmpty = stack.isEmpty();
24 System.out.println("Is stack empty: " + isEmpty);
25
26 // Get the size of the stack
27 int size = stack.size();
28 System.out.println("Size of the stack: " + size);
29 }
30
31}
xxxxxxxxxx
31
}
import java.util.Stack;
public class Main {
public static void main(String[] args) {
// Create a stack
Stack<Integer> stack = new Stack<>();
// Push elements onto the stack
stack.push(5);
stack.push(10);
stack.push(15);
// Pop an element from the stack
int element = stack.pop();
System.out.println("Popped element: " + element);
// Get the top element of the stack without removing
int top = stack.peek();
System.out.println("Top element: " + top);
// Check if the stack is empty
boolean isEmpty = stack.isEmpty();
System.out.println("Is stack empty: " + isEmpty);
// Get the size of the stack
int size = stack.size();
System.out.println("Size of the stack: " + size);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment