
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Stack in Java
A stack class is provided by the Java collection framework and it implements the Stack data structure. The stack implements LIFO i.e. Last In First Out. This means that the elements pushed last are the ones that are popped first.
The following are some of the methods.
Sr.No | Methods & Description |
---|---|
1 |
boolean empty() Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements. |
2 |
Object peek( ) Returns the element on the top of the stack, but does not remove it. |
3 |
Object pop( ) Returns the element on the top of the stack, removing it in the process. |
4 |
Object push(Object element) Pushes the element onto the stack. Element is also returned. |
5 |
int search(Object element) Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned. |
A program that demonstrates stack in Java is given as follows −
Example
import java.io.*; import java.util.*; public class Example { public static void main (String[] args) { Stack<Integer> s = new Stack<Integer>(); s.push(5); s.push(1); s.push(9); s.push(4); s.push(8); System.out.print("The stack is: " + s); System.out.print("\nThe element popped is: "); Integer num1 = (Integer) s.pop(); System.out.print(num1); System.out.print("\nThe stack after pop is: " + s); Integer pos = (Integer) s.search(9); if(pos == -1) System.out.print("\nThe element 9 not found in stack"); else System.out.print("\nThe element 9 is found at position " + pos + " in stack"); } }
Output
The stack is: [5, 1, 9, 4, 8] The element popped is: 8 The stack after pop is: [5, 1, 9, 4] The element 9 is found at position 2 in stack
Now let us understand the above program.
Five elements are pushed into the stack. Then the stack is displayed. After that the top element is popped and that is displayed. The code snippet that demonstrates this is given as follows −
Stack<Integer> s = new Stack<Integer>(); s.push(5); s.push(1); s.push(9); s.push(4); s.push(8); System.out.print("The stack is: " + s); System.out.print("\nThe element popped is: "); Integer num1 = (Integer) s.pop(); System.out.print(num1); System.out.print("\nThe stack after pop is: " + s);
After that, the element 9 is searched in the stack. If it is there, its position is displayed otherwise it is displayed that element is not in stack. The code snippet that demonstrates this is given as follows.
Integer pos = (Integer) s.search(9); if(pos == -1) System.out.print("\nThe element 9 not found in stack"); else System.out.print("\nThe element 9 is found at position " + pos + " in stack");