java.util.Stack Class

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top. When a stack is first created, it contains no items.

Stack class has following constructors.

java.util.Stack Class Constructors

Stack()

Creates an empty Stack.

In this tutorial you can learn about java.util.Stack class and its examples. And also learn how to use java.util.Stack class.

java.util.Stack class Example
/* Save with file name StackExample.java */

public class StackExample
{
	public static void main(String args[])
	{
		//java.util.Vector DECLARATION
		java.util.Stack s;

		//java.util.Stack OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		s = new java.util.Stack();

		//ADD AN ELEMENT
		//Pushes an item onto the top of this Stack
		s.push("Element1");

		//ADD ANOTHER ELEMENT
		//Pushes an item onto the top of this Stack
		s.push("Element2");

		//Looks at the object at the top of this stack
		//without removing it from the stack.
		System.out.println("Next : " + s.peek());

		//CHECK IF THE Stack IS EMPTY
		System.out.println("Stack is Empty : " + s.empty());

		//Element2 WILL BE DELETED
		s.pop();

		//SEARCH AN ELEMENT
		System.out.println("Element At : " + s.search("Element1"));
	}
}
                        
java.util.Stack class Example 2
/* Save with file name StackExample2.java */

public class StackExample2
{
	public static void main(String args[])
	{
		//java.util.Vector DECLARATION
		java.util.Stack s;

		//java.util.Stack OBJECT CREATION
		//USING DEFAULT CONSTRUCTOR
		s = new java.util.Stack();

		//RETURNS Stack CAPACITY
		//METHOD INHERITED FROM Vector Class
		System.out.println("Stack Capacity : " + s.capacity());

		//ADD AN ELEMENT
		//Pushes an item onto the top of this Stack
		s.push("Element1");

		//ADD ANOTHER ELEMENT
		//Pushes an item onto the top of this Stack
		s.push("Element2");

		//ADD ANOTHER ELEMENT
		//METHOD INHERITED FROM Vector Class
		s.add("Element3");

		//RETURNS COUNT OF ELEMENTS Stack CONTAINS
		System.out.println("Elements Count : " + s.size());

		//java.util.Stack OUTPUT
		java.util.Enumeration e = s.elements();
		while(e.hasMoreElements())
		{
			System.out.println("Element : " + e.nextElement());
		}
	}
}