Stack in Java

Stack in Java

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. When a stack is first created, it contains no items. Creation of Stack using Array and Linked List has been explained here.

In addition to method provided by its base class Vector, Stack provides following methods.

[table “” not found /]

Example of Stack.

package com.core2succeed;

import java.util.Stack;

public class StackExample {
	public static void main(String[] args) {
		Stack stack = new Stack();
		//check whether stack is empty or not.
		System.out.println("Is stack empty : "+stack.isEmpty());
		
		//push operation.
		stack.push("New York");
		print(stack);
		stack.push("London");
		print(stack);
		
		//search operation.
		System.out.println("Search New York : "+stack.search("New York"));
		System.out.println("Search Mumbai : "+stack.search("Mumbai"));
		
		//retrieve the top element
		System.out.println("City at top position in Stack: "+stack.peek());
	}
	
	private static void print(Stack stack) {
		System.out.println("Content of Stack : "+stack);
	}
}

Output

Content of Stack : [New York]
Content of Stack : [New York, London]
Search New York : 2
Search Mumbai : -1
City at top position in Stack: London

Leave a Reply

Your email address will not be published. Required fields are marked *