Support our educational content for free when you purchase through links on our site. Learn more
Stack Program in Java Using Scanner [2024]
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
- Quick Tips and Facts
- Background: Understanding the Stack Data Structure
- Creating a Stack Program in Java
- Working with Push, Pop, and Peek Operations
- Time and Space Complexities
- Implementing a Stack Class in Java
- Using Java’s Built-in Stack Class
- Taking Stack Input in Java
- Checking Stack in Java
- FAQ
- Conclusion
- Recommended Links
- Reference Links
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!
- 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
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
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
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
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
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
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
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
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
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!
Recommended Links
- Game Development
- Programming Languages
- Java Development
- Software Architecture
- JavaScript Frameworks
- How to Access Stack Elements in Java? 2024
Reference Links
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!