peek(): This method is available in java.util.Stack class of Java.
Syntax:
K java.util.Stack.peek()
This method looks at the object at the top of this stack without removing it from the stack.
Parameters: NA
Returns: the object at the top of this stack.
Throws:
EmptyStackException - if this stack is empty.
Approach 1: When no exception
Java
import java.util.Stack;public class Stackpeek {public static void main(String[] args) {Stack<Integer> st = new Stack<>();st.push(1);st.push(18);st.push(29);st.push(8);System.out.println(st.peek());}}
Output:
8
Approach 2: EmptyStackException
Java
import java.util.Stack;public class Stackpeek {public static void main(String[] args) {Stack<Integer> st = new Stack<>();System.out.println(st.peek());}}
Output:
Exception in thread "main" java.util.EmptyStackException at java.base/java.util.Stack.peek(Stack.java:101)
No comments:
Post a Comment