The following example shows how to use Stack.peek API and related operations.
Stack provides the following APIs,
public synchronized E peek()
- Returns the object at top of stack without remove it from stack.
public E push(E paramE)
- Pushes an element onto the top of stack.
public synchronized E pop()
- Removes the element at top of stack.
//Current top of stack
System.out.println("Current top of the stack : " + stack.peek());
//Remove the top of stack
System.out.println("Popped : " + stack.pop());
//Current top of stack
System.out.println("Current top of the stack : " + stack.peek());
//Remove the top of stack
System.out.println("Popped : " + stack.pop());
//Current top of stack
System.out.println("Current top of the stack : " + stack.peek());
}
}
It gives the following output,
Stack : [ONE, TWO, THREE, FOUR]
Current top of the stack : FOUR
Popped : FOUR
Current top of the stack : THREE
Popped : THREE
Current top of the stack : TWO