Table of Contents
The Stack class in the Java Collection framework models and implements a stack in java data structure. The basic principle of last-in-first-out governs the class. Aside from the basic push and pop operations, the class also includes three additional functions: empty, search, and peek. The class also extends Vector and treats the class as a stack with the functions mentioned. The class can also be referred to as a Vector subclass. The Vector class is extended by the stack in java class. It allows you to add new elements to the stack, view existing elements in the stack, update existing elements in the stack, and delete all elements from the stack. Data is processed in a first-in-last-out (FILO) order by stacks. This means that you can only add or remove items from the stack’s top. The Java Stack class, on the other hand, has access to over 40 other methods that it inherits from the Vector class.
How to Create a Stack?
1: What is the default value of a boolean in Java?
To make a stack in java, import the java.util.stack package and use the Stack() function Object() { [native code] } of this class. The example below creates an empty Stack.
Stack<E> stack = new Stack<E>();
Here E is the type of Object.
Example:
- Java
// Java code for stack implementation import java.io.*; import java.util.*; class Test { // Pushing element on the top of the stack static void stack_push(Stack<Integer> stack) { for ( int i = 0 ; i < 5 ; i++) { stack.push(i); } } // Popping element from the top of the stack static void stack_pop(Stack<Integer> stack) { System.out.println( "Pop Operation:" ); for ( int i = 0 ; i < 5 ; i++) { Integer y = (Integer) stack.pop(); System.out.println(y); } } // Displaying element on the top of the stack static void stack_peek(Stack<Integer> stack) { Integer element = (Integer) stack.peek(); System.out.println( "Element on stack top: " + element); } // Searching element in the stack static void stack_search(Stack<Integer> stack, int element) { Integer pos = (Integer) stack.search(element); if (pos == - 1 ) System.out.println( "Element not found" ); else System.out.println( "Element is found at position: " + pos); } public static void main (String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack_push(stack); stack_pop(stack); stack_push(stack); stack_peek(stack); stack_search(stack, 2 ); stack_search(stack, 6 ); } } |
Output:
Pop Operation: 4 3 2 1 0 Element on stack top: 4 Element is found at position: 3 Element not found
Learn Coding in your Language! Enroll Here!
Populating a Stack
The push() method is one of the Stack class’s five primary methods. It pushes a single item that has the same data type as the stack implementation in java to the top of the Stack.
// populate a stack
Customers.push(“Jane Doe”);
Customers.push(“John Doe”);
Customers.push(“Patrick Williams”);
Customers.push(“Paul Smith”);
Customers.push(“Erick Rowe”);
Customers.push(“Ella Jones”);
Customers.push(“Jessica Brown”);
The code above adds seven items to the Customers’ stack implementation in java. Each new item is pushed to the top of the Stack. So Jessica Brown is at the top of the Customers Stack. You can also confirm this with the Stack peek() method. The peek() method does not accept any arguments. It returns the topmost object in the Stack without removing it.
// view object at the top of a stack
System.out.println(Customers.peek());
The code above returns the following output to the console:
Jessica Brown
View the Items in a Stack
The stack data structure is quite limited in how you can interact with its data. You should primarily use a Stack through its topmost item. However, you can access arbitrary elements by using methods inherited from the Vector class. element and remove elemental are two examples.
Printing a Stack’s contents is the simplest way to get an overview of its contents. System.out expects a Stack object. A nice summary will be produced by println and the Stack’s function toString() { [native code] }() method:
// view all elements of a stack
System.out.println(Customers);
The code above prints the following output to the console:
[Jane Doe, John Doe, Patrick Williams, Paul Smith, Erick Rowe, Ella Jones, Jessica Brown]
Power up your career with Entri Elevate – Full Stack Development Course!
Searching for an Item Position in a Stack
If you know the index position of an item in the Stack, you can determine its position relative to the top of the Stack. The indexOf() method returns the index position of an item in the stack implementation in java. Keep in mind that a Stack begins indexing its items at zero.
// find an item index position
System.out.println(Customers.indexOf("Jane Doe"));
The code above prints the following output to the console:
0
The search() method is one of the most important methods in the Stack class. It returns an item position relative to the top of the stack, with the top item having position number one.
System.out.println(Customers.search("Jane Doe"));
The code above prints the following output to the console:
7
If you supply the search() or the indexOf() methods with an item that is not in the Stack, they will return a negative one.
System.out.println(Customers.search("Elsa Doe"));
System.out.println(Customers.indexOf("Elsa Doe"));
The code above prints the following output to the console:
-1
-1
Updating Items in a Stack
Only items at the top of a Stack can be manipulated. If you want to update an element that is not at the top of the Stack, you must pop everything above it. One of the most important methods of the Stack is pop(). The pop() method does not accept any arguments. It removes and returns the item at the top of the stack.
// update an object
Customers.pop();
Customers.pop();
Customers.push("Ella James");
Customers.push("Jessica Brown");
System.out.println(Customers);
The code above prints the following output to the console:
[Jane Doe, John Doe, Patrick Williams, Paul Smith, Erick Rowe, Ella James, Jessica Brown]
As the output shows, the code changes Ella’s surname to James. It entails a process of popping items from the stack until you reach the target object. It then pops the target object, updates it, and returns it to the stack, along with the items that were on top of it. Each time you want to update an item in your Stack, you must use a program that performs operations like the one described above.
Deleting an Item From a Stack
To remove a single item from the Stack data structure, use the pop() method once more. If the item you want to delete is not at the top, you can pop up items until you find it.
Power up your career with Entri Elevate – Full Stack Development Course!
Deleting All the Items in a Stack
You can use a Java while loop with the pop() method to delete all the elements from a Stack one at a time. However, using the clear() method is a more efficient approach. The clear() method is inherited by the Stack class from the Vector class. It accepts no arguments and returns nothing; it simply removes all elements from the Stack data structure.
// delete all items in a stack
Customers.clear();
System.out.println(Customers.empty());
The preceding code removes all items from the Customers Stack. The empty() method is then used to determine whether the Stack is empty. Another primary method of the Java Stack Class is empty(). It does not accept any arguments and returns a Boolean value. If the Stack is empty, this method returns true; otherwise, it returns false.
The code above prints the following output to the console:
true
Practical Applications for the Stack Data Structure
The Stack data structure is extremely limited. It does not offer as much data processing flexibility as other data structures. This begs the question, when should the Stack data structure be used?
The Stack data structure is ideal for applications that require reverse data processing. These are some examples:
A program that determines whether a word is a palindrome.
A program for converting decimal numbers to binary numbers.
Applications that allow users to undo previous actions.
Games that allow the user to return to previous moves, such as chess.
Learn Coding in your Language! Enroll Here!
Methods in the Stack class
push():
The push() method moves an element passed as a parameter to the top of the stack.
pop():
The pop() method removes and returns the stack’s top element.
If we call the pop() method on an empty stack, an EmptyStackException exception is thrown.
peek():
The peek() method returns the topmost element of the stack without removing it.
empty():
If the stack is empty, the empty() method returns true; otherwise, it returns false.
Object element search:
The search() method determines whether an object, which is the input parameter of the function, exists in the stack or not.
If the element is found, it returns the position (as an integer) of the element from the top of the stack otherwise.
If you are interested to learn new coding skills, the Entri app will help you to acquire them very easily. Entri app is following a structural study plan so that the students can learn very easily. If you don’t have a coding background, it won’t be a problem. You can download the Entri app from the google play store and enroll in your favorite course.