Useful Java Code Snippets 11 - The Stack Class in Java



Hello everyone, today's code snippet is about stacks. A stack is a data structure that allows data to be inserted (a 'push' operation), and removed (a 'pop' operation).  




A stack is a LIFO-queue (Last In First Out). Let me explain this with the example figure given on the side. As can be seen from this figure, the rocks are piled up on top of each other. If you want to remove one of these rocks from this stack, which one would you prefer?.. I would prefer the top one (the last added one), since it is the easiest rock to remove..This is how stacks in java work as well. The one that added to the stack last, leaves first and the one added to the stack first, leaves last. In the following snippet, user adds to and removes data from a stack by using the push-pop methods of the Stack class of Java;

Main.java

/**
* Author : Berk Soysal
*/

package herrberk;

import java.util.Scanner;
import java.util.Stack;

public class Main {

 // Scanner objects to read information from the console
 private static final Scanner intsc = new Scanner(System.in);
 private static final Scanner strsc = new Scanner(System.in);

 // Shows the pushed element to the stack and the stack itself after the push 
 private static void showPush(Stack st, int b) {
   st.push(new Integer(b));
   System.out.println("Push "+ b + " to the stack");
   System.out.println("stack: " + st);
 }

 // Shows the popped element from the stack
 private static void showPop(Stack st){
  Integer a = (Integer) st.pop();
  System.out.println("Removed "+ a + " from the stack");
  System.out.println("stack: " + st);
 }

 // Main function
 public static void main(String[] args) {

  int a, i=3;//number of elements desired (stack capacity)
  Stack st = new Stack ();

  System.out.println("Stack is empty!");
  
  // Loop to push integers 
  while (i-- > 0){
    System.out.println("Enter an integer: ");
    a = intsc.nextInt();
    showPush(st, a);
  }
  
  // User enters 0 to empty the stack
  System.out.println("Press Enter 0 to empty the stack"); 
  String ss = strsc.nextLine();

  if(ss.contentEquals("0")){
    while (!st.empty()){  
      showPop(st);
    }
  }
  else { 
    System.out.println("Stack remains full !");
    System.exit(1);
  }
 }
}


Output: 

Stack is empty!
Enter an integer:
953
Push 953 to the stack
stack: [953]
Enter an integer:
442
Push 442 to the stack
stack: [953, 442]
Enter an integer:
555
Push 555 to the stack
stack: [953, 442, 555]
Press Enter 0 to empty the stack
0
Removed 555 from the stack
stack: [953, 442]
Removed 442 from the stack
stack: [953]
Removed 953 from the stack
stack: []


Please leave a comment if you have any questions, comments or suggestions. Thanks..
Author:

Software Developer, Codemio Admin

Disqus Comments Loading..