Stack methods
- Eclipse: Oxygen
- Java: 1.8
The useful stack methods that are a push(), pop(), and search() along with empty() methods are shown here. These methods are used to perform basic operations. In this tutorial, users will learn how to define a stack along with the use of all the above-stated methods.
The following program will demonstrate stack methods:
A stack of Integer type is created, the push method is used to push elements in the stack. A foreach loop is used to iterate through all the elements of the stack.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Stack; public class App { public static void main(String[] args) { Stack<Integer> demo = new Stack<>(); demo.push(0); demo.push(1); demo.push(2); demo.push(3); demo.push(4); demo.push(5); for(Integer temp:demo) { System.out.println(temp); } } } |
Output
0
1
2
3
4
5
pop() method is always performed on the top of stack element. If we perform pop() operation, it will remove the top element of the stack.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class App { public static void main(String[] args) { Stack<Integer> demo = new Stack<>(); demo.push(0); demo.push(1); demo.push(2); demo.push(3); demo.push(4); demo.push(5); demo.pop(); for(Integer temp:demo) { System.out.println(temp); } } } |
Output
0
1
2
3
4
Peek() method is used to check the last element of the stack.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class App { public static void main(String[] args) { Stack<Integer> demo = new Stack<>(); demo.push(0); demo.push(1); demo.push(2); demo.push(3); demo.push(4); demo.push(5); demo.pop(); System.out.println(demo.peek()); for(Integer temp:demo) { System.out.println(temp); } } } |
We can also check if empty or not by using the empty() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class App { public static void main(String[] args) { Stack<Integer> demo = new Stack<>(); demo.push(0); demo.push(1); demo.push(2); demo.push(3); demo.push(4); demo.push(5); demo.pop(); System.out.println(demo.peek()); if(demo.isEmpty()){ System.out.println("Stack is empty"); }else{ System.out.println("Stack is not empty"); } } } |
Output
Stack is not empty
We can also perform a search operation on stack. Search() method returnsĀ 1 if it finds the searched element and it returns -1 if it does not find the searched element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class App { public static void main(String[] args) { Stack<Integer> demo = new Stack<>(); demo.push(0); demo.push(1); demo.push(2); demo.push(3); demo.push(4); demo.push(5); demo.pop(); if(demo.isEmpty()){ System.out.println("Stack is empty"); }else{ System.out.println("Stack is not empty"); } System.out.println(demo.search(56)); } } |
Output
Stack is not empty
-1
Contributed by: Poonam Tomar