LIFO java stack code example

Example 1: java stack

// construct with non-primative elements only!
Stack<String> stack = new Stack<String>();

// to add a value to the top of the stack:
stack.push("Hello");

// to return and remove a value from the top:
String top = stack.pop();

// to return a value without removing it:
String peek = stack.peek();

Example 2: java stack pop

package com.tutorialspoint;

import java.util.*;

public class StackDemo {
   public static void main(String args[]) {

      // creating stack
      Stack st = new Stack();

      // populating stack
      st.push("Java");
      st.push("Source");
      st.push("code");

      // removing top object
      System.out.println("Removed object is: "+st.pop());

      // elements after remove
      System.out.println("Elements after remove: "+st);
   }    
}

Tags:

Java Example