Advanced Java:
Utilizing Stacks in Java
To create a stack, Java employs a built-in data structure known as a Stack.
For the Push operation, we use push(), which adds an element at the
stack's end. For the Pop operation, there's the pop() function that removes
the last element, simulating the removal of the 'top' element in a stack.
Here's how it looks:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>(); // A new empty stack
// Push operations
stack.push("John");
stack.push("Mary");
stack.push("Steve");
stack.pop(); // Pop operation removes 'Steve'
System.out.println(stack); // Outputs: [John, Mary]
}
}
In the example provided, we push 'John', 'Mary', and 'Steve' into the stack
and then pop 'Steve' from the stack.
Advanced Stack Operations
Stack operations go beyond merely push and pop. For example, to verify if
a stack is empty, we can use the empty() method. If it returns true, that
means the stack is empty. Conversely, if it returns false, we can infer the
stack is not empty. To peek at the top element of the stack without
popping it, we use the peek() method.
public class StackOperations {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Steve");
stack.push("Sam");
System.out.println(stack.peek()); // Outputs: 'Sam'
System.out.println(stack.empty()); // Outputs: false
stack.pop(); // Remove 'Sam'
stack.pop(); // Remove 'Steve'
System.out.println(stack.empty()); // Outputs: true
}
}
In this example, 'Sam' is added (pushed), and then the topmost stack
element, which is 'Sam', is peeked.
Practical Stack Applications: Reversing a String
Practical applications of stacks in Java are plentiful. Here is one of them
— reversing a string.
We will push all characters into a stack and then pop them out to get a
reversed string!
public class ReverseString {
public static String reverseString(String input) {
Stack<Character> stack = new Stack<>();
for (char c : input.toCharArray()) {
stack.push(c);
}
StringBuilder reversedString = new StringBuilder();
while (!stack.empty()) {
reversedString.append(stack.pop());
}
return reversedString.toString();
}
public static void main(String[] args) {
System.out.println(reverseString("HELLO")); // Outputs: OLLEH
}
}