Stack Class in Java

In Java, a stack is a data structure that allows us to store items in a Last In First Out (LIFO) manner. This means that the last item we push onto the stack will be the first item that we pop off of it.

One of the main benefits of using a stack is that it allows us to easily keep track of the order in which items are added and removed. This is because each time an item is added to the stack (also known as “pushing” an item onto the stack), it is placed on top of all the other items. When an item is removed from the stack (also known as “popping” an item off the stack), it is always the one that was most recently added.

In Java, the stack class is implemented using a generic type, meaning that it can be used to store any type of object. This allows us to create a stack of any type, such as a stack of integers or a stack of strings.

To use the stack class in our Java code, we will need to import the java.util.Stack package. Once we have done this, we can create a new stack by calling the stack’s constructor. For example:

Stack<String> stack = new Stack<>();

This creates a new stack that is capable of storing strings.

We can add items to the stack by calling the push() method and passing in the item we want to add. For example:

stack.push("item 1");
stack.push("item 2");
stack.push("item 3");

This will add three items to the stack, with “item 3” being at the top of the stack.

The stack class also provides several other methods that we may find useful. These include:

  • peek(): This method returns the item at the top of the stack without removing it.
  • empty(): This method returns true if the stack is empty and false if it is not.
  • search(item): This method returns the position of the specified item in the stack, with the top of the stack being considered position 1.

The complete example is given below:

import java.util.Stack;

public class StackDemo {
	public static void main(String[] args) {
		Stack<String> stack = new Stack<>();
		stack.push("item 1");
		stack.push("item 2");
		stack.push("item 3");
		
		System.out.println(stack);
		
		String firstValue = stack.peek(); // This returns the last added item from the stack
		System.out.println(firstValue);
	}
}

The output of the above code will be:

[item 1, item 2, item 3]
item 3

To remove an item from the stack, we can call the pop() method. This will remove the item at the top of the stack and return it to us. For example:

String item = stack.pop();

This will remove “item 3” from the top of the stack and assign it to the “item” variable.

The stack class is a useful tool for storing and manipulating items in a LIFO manner in Java. By using this class, we can easily keep track of the order in which items are added and removed, and take advantage of the various methods it provides to manipulate the stack.