The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and classes to store the collection of objects.
The stack data structure has the two most important operations that are push and pop. The push operation inserts an element into the stack and pop operation removes an element from the top of the stack.
Java Stack Example :
Example 1 :
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("jack");
stack.push("john");
stack.push("jacob");
System.out.println("Before Pop");
System.out.println(stack);
stack.pop();
System.out.println("After Pop");
System.out.println(stack);
Example 2 :
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Length:");
int number = scanner.nextInt();
scanner.nextLine();
for (int i= 1;i<=number;i++)
{
stack.push(scanner.nextLine());
}
System.out.println("Before Pop");
System.out.println(stack);
System.out.println("Pop Count:");
int popNumber = scanner.nextInt();
scanner.nextLine();
for (int i=1;i<=popNumber; i++)
{
stack.pop();
}
System.out.println(stack);
}
}
Top comments (0)