peek() method get the top element of this stack without removing it from the stack.
/**
* @author lautturi.com
* Java example:Stack class peek() method in Java
*/
import java.util.*;
import java.util.regex.Pattern;
public class Lautturi {
public static void main(String[] args){
Stack<Character> stack = new Stack<Character>();
stack.push('A');
stack.push('B');
stack.push('C');
stack.push('D');
System.out.println(stack);
Character ch = stack.peek();
System.out.println("Element at top: " + ch);
}
}Soural.www:ecutturi.comoutput:
[A, B, C, D] Element at top: D