Stack in Java

Facebooktwitterredditpinterestlinkedinmailby feather

The Stack is the child class of Vector. The Stack class extends the Vector class with five operations. These operations allow a vector to be treated as a Stack. Stack represents a LIFO (Last In First Out) order of objects. It usually provides the push and pop operations as well as a method to peek at the last item on the Stack. It provides a method to test whether the stack is empty or not and a method to search an element in the Stack to discover how far it is from the top.

When a Stack is initialized, it is empty or contains no items.

Syntax to create a Stack:

This constructor creates an empty Stack with the name s.

Methods of Stack and its usages:

Modifier and Data Type Methods Description
Boolean empty() The method tests if the stack is empty or not.
Object E push(E item) This method pushes (insert) an item onto the top of the stack.
  pop() It removes the element from the top of the stack and returns that element as the value of this method.
  peek() This method returns the element from the top of the stack without removing it from the stack.
int Search(Object o) This method determines if an element exists in the stack. If the element is present in the stack, then it returns the index position of that element from the top of the stack. Otherwise, it returns -1.

Example to illustrate the push() method.

Output:

Example to illustrate pop() method.

Output:

Example to illustrate the peek() method.

Output:

Example to illustrate empty() method.

Output:

Example to illustrate search() method.

Output:

Facebooktwitterredditpinterestlinkedinmailby feather