1// construct with non-primative elements only!
2Stack<String> stack = new Stack<String>();
3
4// to add a value to the top of the stack:
5stack.push("Hello");
6
7// to return and remove a value from the top:
8String top = stack.pop();
9
10// to return a value without removing it:
11String peek = stack.peek();
1import java.util.Stack<E>;
2Stack<Integer> myStack = new Stack<Integer>();
3myStack.push(1);
4myStack.pop();
5myStack.peek();
6myStack.empty(); // True if stack is empty
1package com.tutorialspoint;
2
3import java.util.*;
4
5public class StackDemo {
6 public static void main(String args[]) {
7
8 // creating stack
9 Stack st = new Stack();
10
11 // populating stack
12 st.push("Java");
13 st.push("Source");
14 st.push("code");
15
16 // removing top object
17 System.out.println("Removed object is: "+st.pop());
18
19 // elements after remove
20 System.out.println("Elements after remove: "+st);
21 }
22}