# Stack



1. push
2. pop
3. peek
4. poll
5. search

```java
import java.util.Stack;

public class StackExample {

	public static void main(String[] args) {
			
		Stack<Integer>  gymWeights =  new Stack<Integer>();
		
		//push
		gymWeights.push(25);
		gymWeights.push(20);
		gymWeights.push(15);
		gymWeights.push(10);

		System.out.println(gymWeights);
		
		//pop remove the top element
		int weight = gymWeights.pop();
		
		System.out.println(weight);
		
		System.out.println(gymWeights);
		
		//peek
		int num = gymWeights.peek();
		System.out.println(num);
		System.out.println(gymWeights);
		
		//search
		int pos = gymWeights.search(20);
		System.out.println(pos);
		
		//exception
		Stack<String> urls = new Stack<String>();
		
		urls.push("www.abc.com");
		
		System.out.println(urls.pop());
		//now stack is empty
		System.out.println(urls.pop());
				


	}

}
```

```java
[25, 20, 15, 10]
10
[25, 20, 15]
15
[25, 20, 15]
2
www.abc.com
Exception in thread "main" java.util.EmptyStackException
	at java.util.Stack.peek(Stack.java:102)
	at java.util.Stack.pop(Stack.java:84)
	at StackExample.main(StackExample.java:40)
```

![](https://2172743581-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-La4k4liN--SZ6ay4iod%2F-LanpOGdgv3_J537-CNX%2F-LanqyqJsDl1ItCx250Q%2Fassets_-LTkdx_CHE-ubFCrKQ7__-L_k2pOS3gHVu6XrKwWQ_-L_k5gNaDtDwsSqRtwkv_Screen%20Shot%202019-03-12%20at%209.35.42%20AM.png?alt=media\&token=e9babdbb-1223-494c-92f8-15ad57128065)

### Problems:

{% embed url="https://www.hackerrank.com/challenges/java-stack/problem" %}

