java collections 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: stack class in java

import java.util.Stack;
class Main {
    public static void main(String[] args) {
        Stack<String> animals= new Stack<>();
        // Add elements to Stack
        animals.push("Dog");
        animals.push("Horse");
        // Remove element from Stack
      	animals.pop();
      	// Access element from top of Stack
      	animals.peek();
    }
}

Example 3: 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