Enroll in Selenium Training

Stack

In programming, a stack is a collection of objects that serve two principal operations:

  • push: add an element to the collection
  • pop: get and remove the most recently pushed element

Stack

The Stack class represents a last-in-first-out (LIFO) stack of objects. While a Vector starts index at 0, a Stack starts index at 1. It extends class Vector with five operations that allow a vector to be treated as a stack. The additional operations are:

// Tests if this stack is empty.
boolean empty();

// Read the object at the top of this stac
E   peek()

// Retrieve and remove the object at the top of this stack
E   pop()

// Pushes an item onto the top of this stack.
E   push(E item)

// Find the position of an object in this stack
int search(Object o)

Example

We demonstrate how peek(), pop, push behave in the following example. Be sure to check if the stack is empty() before calling peek() or pop() to avoid the EmptyStackException exception.

import java.util.Stack;

public class StackTest {
	public static void printStack(Stack<String> words) {
		System.out.print("[");
		while(!words.empty()) {
			System.out.print(words.pop() + " ");
			}
		System.out.println("]");
	}

	public static void find(Stack<String> words, String w) {
		int idx = words.search("thrive");
		if (idx < 0) {
			System.out.println(w + " not found in this stack");
		} else {
			System.out.println("Index of [" + w + "] is: " + idx);
		}
	}

	public static void main(String []args) {
		Stack<String> words = new Stack<String>();
		// append
		words.push("thrive");
		words.push("at");
		words.push("work");		
		System.out.println("Peek is: [" + words.peek() + "]");

		System.out.println("> Before pop ");
		find(words, "thrive");
		printStack(words);
		System.out.println("> After pop ");
		find(words, "thrive");
	}

}

The above code produces:

Peek is: [work]

>Before pop Index of [thrive] is: 3 [work at thrive ]

>After pop thrive not found in this stack

Summary

  • The Stack class extends the Vector class to support operations on stack. These operations include: push, pop, peek, empty and search.
  • Stack index starts at 1.
  • It is better to ensure that the stack is not empty before calling pop and peek.
Lakshay Sharma
I’M LAKSHAY SHARMA AND I’M FULL STACK TEST AUTOMATION ENGINEER. Have passed 12 years playing with automation in mammoth projects like O2 (UK), Sprint (US), TD Bank (CA), Canadian Tire (CA), NHS (UK) & ASOS(UK). Currently I am working with KNAB bank as SDET. I am passionate about designing Automation Frameworks that follow OOPS concepts and Design patterns. https://www.linkedin.com/in/lakshay-sharma-a4216312/
Reviewers
Virender Singh's Photo
Virender Singh

Similar Articles