The perfect place for easy learning...

Java Programming

×

Topics List


Stack class in java





In java, the package java.util contains a class called Stack which is a child class of Vector class. It implements the standard principle Last-In-First-Out of stack data structure.

The Stack has push method for inesrtion and pop method for deletion. It also has other utility methods.

🔔 In Stack, the elements are added to the top of the stack and removed from the top of the stack.

The Stack class in java has the following constructor.

S. No. Constructor with Description
1 Stack( )

It creates an empty Stack.

The Stack class in java has the following methods.

S.No. Methods with Description
1 Object push(Object element)

It pushes the element onto the stack and returns the same.

2 Object pop( )

It returns the element on the top of the stack and removes the same.

3 int search(Object element)

If element found, it returns offset from the top. Otherwise, -1 is returned.

4 Object peek( )

It returns the element on the top of the stack.

5 boolean empty()

It returns true if the stack is empty, otherwise returns false.

Let's consider an example program to illustrate methods of Stack class.

Example
import java.util.*;

public class StackClassExample {

	public static void main(String[] args) {

		Stack stack = new Stack();
		
		Random num = new Random();
		
		for(int i = 0; i < 5; i++)
			stack.push(num.nextInt(100));
		
		System.out.println("Stack elements => " + stack);
		
		System.out.println("Top element is " + stack.peek());
		
		System.out.println("Removed element is " + stack.pop());
		
		System.out.println("Element 50 availability => " + stack.search(50));
		
		System.out.println("Stack is empty? - " + stack.isEmpty());

	}

}

When we execute the above code, it produce the following output.

Stack class in java