Java Stack Class Tutorial with Examples

The stack is a subclass of vector class in Java. It basically based on LIFO structure that is Last In First Out structure. It has two methods and they are push and pop but as it extends Vector class it gets three more methods search, peek and empty method. By using these methods you can do insert, remove, search etc. operation.

Stack class only has one constructor which is a default constructor. Because of this, you can only create an empty stack.

Commonly used methods

Following are the commonly used methods of Stack Class.

Methoddescription
Object push(Object item)Pushes the object item in the stack and also returns the same object.
Object pop()Return the element on the top of stack by removing it
Object peek()Return the element on the top of stack without removing it
boolean empty()Returns true if stack is empty
int search(Object item)Finds the item in the stack and if found returns its position couting from top of stack otherwise returns -1

Examples

Following programs creates a empty stack and implements five methods provided by stack class.

The output should be:

Is stack empty: true
Pushed item: 5
Is stack empty: false
Pushed item: 6
Pushed item: 7
Pushed item: 8
Popped item: 8
Item 8 is not found
Item 5 is found at: 3
Item 7 is found at: 1

LEAVE A REPLY

Please enter your comment!
Please enter your name here