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 empty1import java.util.Stack;
2class Main {
3    public static void main(String[] args) {
4        Stack<String> animals= new Stack<>();
5        // Add elements to Stack
6        animals.push("Dog");
7        animals.push("Horse");
8        // Remove element from Stack
9      	animals.pop();
10      	// Access element from top of Stack
11      	animals.peek();
12    }
13}1// Java code for stack implementation 
2
3import java.io.*; 
4import java.util.*; 
5
6class Test 
7{ 
8	// Pushing element on the top of the stack 
9	static void stack_push(Stack<Integer> stack) 
10	{ 
11		for(int i = 0; i < 5; i++) 
12		{ 
13			stack.push(i); 
14		} 
15	} 
16	
17	// Popping element from the top of the stack 
18	static void stack_pop(Stack<Integer> stack) 
19	{ 
20		System.out.println("Pop Operation:"); 
21
22		for(int i = 0; i < 5; i++) 
23		{ 
24			Integer y = (Integer) stack.pop(); 
25			System.out.println(y); 
26		} 
27	} 
28
29	// Displaying element on the top of the stack 
30	static void stack_peek(Stack<Integer> stack) 
31	{ 
32		Integer element = (Integer) stack.peek(); 
33		System.out.println("Element on stack top: " + element); 
34	} 
35	
36	// Searching element in the stack 
37	static void stack_search(Stack<Integer> stack, int element) 
38	{ 
39		Integer pos = (Integer) stack.search(element); 
40
41		if(pos == -1) 
42			System.out.println("Element not found"); 
43		else
44			System.out.println("Element is found at position: " + pos); 
45	} 
46
47
48	public static void main (String[] args) 
49	{ 
50		Stack<Integer> stack = new Stack<Integer>(); 
51
52		stack_push(stack); 
53		stack_pop(stack); 
54		stack_push(stack); 
55		stack_peek(stack); 
56		stack_search(stack, 2); 
57		stack_search(stack, 6); 
58	} 
59} 
60