
How to use Stack class in java collection?

The Stack class uses the First In Last Out(FILO) mechanism. Here is an example of Stack class.
import java.util.Stack;
public class StackExample {
public static void main(String [] args){
Stack stack = new Stack();
stack.push("Angelina Jolie");
stack.push("Jennifer Aniston");
stack.push("Scarlett Johansson");
stack.push("Reese Witherspoon");
stack.push("Megan Fox");
stack.push("Nicole Kidman");
System.out.println("The elements in the Stack :- " + stack);
System.out.println("The element at the top :- " +stack.peek());
System.out.println("The element poped out of the stack :- " + stack.pop());
System.out.println("The element in a stack after pop out an element- : " +stack);
System.out.println("The result of searching :- " +stack.search(" r u"));
}
}
Output:-
The elements in the Stack :- [Angelina Jolie, Jennifer Aniston, Scarlett Johansson, Reese Witherspoon, Megan Fox, Nicole Kidman] The element at the top :- Nicole Kidman The element poped out of the stack :- Nicole Kidman The element in a stack after pop out an element- : [Angelina Jolie, Jennifer Aniston, Scarlett Johansson, Reese Witherspoon, Megan Fox] The result of searching :- -1
Description:- The above example demonstrates you the Stack class in java collection. We are using three methods of Stack. push(object items): The push method add an items to the top of the Stack. peek(): The peek() method returns the element at the top of the Stack, and pop(): The pop() method remove the element at the top of the Stack and returns the element.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.