Stack in Java

Posted on Updated on

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.

Method Description
push(Object item)  Pushes an item onto the top of the stack.
Object pop()  Removes the object at the top of this stack and returns that object as the value of this function.
Object peek()  Looks at the object at the top of this stack without removing it from the stack.
Boolean empty() Returns true if the stack is empty, and returns false if the stack contains elements.
int search(Object item) Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned.

Example of Stack.


Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.