The Stack class in Java is a implementation of the List interface that implements a last-in, first-out (LIFO) stack. It provides methods for pushing and popping elements, as well as methods for checking the size of the stack and whether it is empty.
Here is an example of how to use a Stack in Java:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
// Create a Stack of integers
Stack<Integer> stack = new Stack<>();
// Push some elements onto the stack
stack.push(1);
stack.push(2);
stack.push(3);
// Pop an element from the stack
int element = stack.pop();
System.out.println("Popped element: " + element);
// Check the size of the stack
int size = stack.size();
System.out.println("Size of stack: " + size);
// Check if the stack is empty
boolean isEmpty = stack.isEmpty();
System.out.println("Stack is empty: " + isEmpty);
}
}
In this example, we create a Stack of integers and push some elements onto it. We pop an element from the stack, check the size of the stack, and check if the stack is empty.
Note that the Stack class is deprecated in Java, and it is recommended to use the Deque interface instead, which provides more flexible stack-like operations.