Stack Class
In this tutorial, we are going to discuss Stack class in java. Java Collection framework provides a Stack class that models and implements a Stack data structure.
The class is based on the basic principle of Last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek.
- It is the child class of Vector.
- Whenever last in first out(LIFO) order required then we should go for Stack.
Constructors
Stack class contains one and only one constructor.
Stack s= new Stack();
Methods in Stack
1. Object push(Object o);
To insert an object into the stack.
2. Object pop();
To remove and return top of the stack.
3. Object peek();
To return top of the stack without removal.
4. boolean empty();
Returns true if Stack is empty.
5. int search(Object o);
Returns offset if the element is available otherwise returns “-1”
package com.ashok.collections;
import java.util.Stack;
/**
*
* @author ashok.mariyala
*
*/
public class MyStack {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("Ashok");
stack.push("Vinod");
stack.push("Naresh");
System.out.println(stack);// [Ashok, Vinod, Naresh]
System.out.println(stack.pop());// Naresh
System.out.println(stack);// [Ashok, Vinod]
System.out.println(stack.peek());// Vinod
System.out.println(stack.search("Ashok"));// 2
System.out.println(stack.search("Dillesh"));// -1
System.out.println(stack.empty());// false
}
}
That’s all about Stack in java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!