Stack Program in Java Using Scanner [2024]

Video: Stack Java Tutorial #65.







Imagine you’re a magician performing a card trick. You stack the cards one on top of the other, and when you need to reveal a card, you take it from the top of the stack. This concept of stacking and retrieving elements is the foundation of the stack data structure. In this article, we’ll explore how to create a stack program in Java using the Scanner class. So grab your wand and let’s dive in!

Table of Contents

Quick Answer

To create a stack program in Java using the Scanner class, you’ll need to understand the stack data structure and its basic operations. We’ll guide you through the process of implementing your own stack class and using Java’s built-in Stack class. So get ready to stack up some knowledge!

Quick Tips and Facts

  • The stack data structure follows the Last In First Out (LIFO) principle.
  • Real-world objects like a stack of plates or a call stack also follow the LIFO principle.

Background: Understanding the Stack Data Structure

graphs of performance analytics on a laptop screen

Before we dive into creating a stack program in Java, let’s take a moment to understand the stack data structure. A stack is a linear data structure that follows the Last In First Out (LIFO) principle. It means that the last element added to the stack is the first one to be removed.

Think of a stack as a pile of books. You can only add or remove books from the top of the stack. Similarly, in a stack data structure, you can only perform operations on the topmost element.

Creating a Stack Program in Java

Video: stack implementation using array in java.







To create a stack program in Java, we’ll start by implementing our own stack class. This will allow us to have full control over the stack operations. Here’s an example of how you can create a stack class in Java:

public class Stack {
    private int maxSize;
    private int[] stackArray;
    private int top;

    public Stack(int size) {
        maxSize = size;
        stackArray = new int[maxSize];
        top = -1;
    }

    public void push(int value) {
        if (top == maxSize - 1) {
            System.out.println("Stack is full. Cannot push element.");
            return;
        }
        stackArray[++top] = value;
    }

    public int pop() {
        if (top == -1) {
            System.out.println("Stack is empty. Cannot pop element.");
            return -1;
        }
        return stackArray[top--];
    }

    public int peek() {
        if (top == -1) {
            System.out.println("Stack is empty. Cannot peek element.");
            return -1;
        }
        return stackArray[top];
    }

    public boolean isEmpty() {
        return (top == -1);
    }

    public boolean isFull() {
        return (top == maxSize - 1);
    }
}

In this example, we have defined a Stack class with the necessary methods for push, pop, peek, isEmpty, and isFull operations. The stackArray is an array that holds the elements of the stack, and the top variable keeps track of the index of the topmost element.

Working with Push, Pop, and Peek Operations

Video: #10 Stack Implementation using Java Part 1 | Push Pop Peek Methods.







Now that we have our stack class, let’s see how the push, pop, and peek operations work. These operations are the basic building blocks of a stack data structure.

  • Push Operation: Adding an element to the stack.
  • Pop Operation: Removing an element from the stack.
  • Peek Operation: Returning the topmost element of the stack without removing it.

Here’s an example of how you can use these operations in your stack program:

public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack(5);

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Top element: " + stack.peek());

        stack.pop();
        stack.pop();

        System.out.println("Top element after popping: " + stack.peek());
    }
}

In this example, we create a stack object with a maximum size of 5. We then push three elements onto the stack and print the top element using the peek operation. After popping two elements from the stack, we again print the top element. The output of this program will be:

Top element: 30
Top element after popping: 10

Time and Space Complexities

Video: 1.5.1 Time Complexity #1.







The time and space complexities of stack operations are important factors to consider when designing and implementing stack programs in Java.

  • The push, pop, and peek operations have a time complexity of O(1), which means they take constant time regardless of the size of the stack.
  • The space complexity of a stack program depends on the number of elements stored in the stack. In our example, the space complexity is O(n), where n is the maximum size of the stack.

Implementing a Stack Class in Java

Video: Stack Implementation Using an Array Java / Stack Using an Array Java.







In the previous section, we created our own stack class from scratch. However, Java provides a built-in Stack class that we can use instead. The Stack class is part of the Java Collections Framework and provides additional methods and functionalities.

Here’s an example of how you can use Java’s built-in Stack class:

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Top element: " + stack.peek());

        stack.pop();
        stack.pop();

        System.out.println("Top element after popping: " + stack.peek());
    }
}

In this example, we import the Stack class from the java.util package. We create a stack object of type Integer and use the push, pop, and peek methods provided by the Stack class.

Taking Stack Input in Java

Video: How To Get Array Input From A User In Java Using Scanner.







To take stack input in Java, we can use the Scanner class. The Scanner class allows us to read user input from the console.

Here’s an example of how you can take stack input using the Scanner class:

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Stack<Integer> stack = new Stack<>();

        System.out.print("Enter the number of elements: ");
        int n = scanner.nextInt();

        System.out.println("Enter the elements:");

        for (int i = 0; i < n; i++) {
            int element = scanner.nextInt();
            stack.push(element);
        }

        System.out.println("Stack elements: " + stack);
    }
}

In this example, we create a Scanner object to read user input from the console. We prompt the user to enter the number of elements they want to push onto the stack. We then use a for loop to iterate over the number of elements and push them onto the stack. Finally, we print the stack elements using the toString() method.

Checking Stack in Java

Video: Stack Data Structure using Java | Stack Data Structure Implementation in Java.







To check if a stack is empty or full in Java, we can use the isEmpty() and isFull() methods respectively. These methods return a boolean value indicating whether the stack is empty or full.

Here’s an example of how you can check the stack in Java:

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        System.out.println("Is stack empty? " + stack.isEmpty());

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Is stack empty? " + stack.isEmpty());
        System.out.println("Is stack full? " + stack.isFull());
    }
}

In this example, we create a stack object and initially check if it is empty. After pushing three elements onto the stack, we again check if it is empty and if it is full. The output of this program will be:

Is stack empty? true
Is stack empty? false
Is stack full? false

FAQ

text

How to create a stack in Java code?

To create a stack in Java, you can either implement your own stack class or use Java’s built-in Stack class. We have covered both approaches in this article.

Read more about “How do you implement stack code? …”

How to take stack input in Java?

To take stack input in Java, you can use the Scanner class to read user input from the console. We have provided an example in this article.

Read more about “How to Access Stack Elements in Java? …”

How to check stack in Java?

To check if a stack is empty or full in Java, you can use the isEmpty() and isFull() methods respectively. We have demonstrated this in the article.

Read more about “What is a Simple Example of Stack? …”

What are the basic operations of a stack in Java?

The basic operations of a stack in Java are push, pop, and peek. We have explained these operations in detail in this article.

Read more about “Queue is a Class or Interface? …”

Conclusion

MacBook Pro with images of computer language codes

In this article, we explored how to create a stack program in Java using the Scanner class. We learned about the stack data structure, its basic operations, and their time and space complexities. We implemented our own stack class and also used Java’s built-in Stack class. We covered how to take stack input and check the stack in Java. Now you have the power to stack up elements and retrieve them with ease!

Remember, whether you’re building a card trick or developing complex software, understanding data structures like the stack can be incredibly useful. So keep stacking knowledge and keep coding!

Now that you have the knowledge to create a stack program in Java using the Scanner class, it’s time to put it into practice. Happy coding!

Jacob
Jacob

Jacob is a software engineer with over 2 decades of experience in the field. His experience ranges from working in fortune 500 retailers, to software startups as diverse as the the medical or gaming industries. He has full stack experience and has even developed a number of successful mobile apps and games.

Articles: 179

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.