DEV Community

Jack Pritom Soren
Jack Pritom Soren

Posted on

4 1

Stack (Java Collections)

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);
Enter fullscreen mode Exit fullscreen mode

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);

    }
}

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs