Author
Software Engineer at Siemens

# Java Stack 101: Delving into the Stack Class

The Stack in Java is a data structure, much like a queue, array, linked list, or tree. Where it differs from the others is that the Java Stack is based on the Last In, First Out (LIFO) principle. What this means is that when you use the two commands to add and remove an element from the stack, the first one you remove will always be the last one you added. Let’s take a closer look at the Java Stack Class

## Exploring the Java Stack Class

The Java Stack Class is an extension of the Vector class, which itself extends the List class. Because vectors are mutable and can grow and shrink with the demands of the elements inside, Stacks can also change sizes on demand. The extension of the Vector class adds five operations that transform a Vector into a Stack. These five operations are:
• .push(E item) – places an element onto the top of the stack
• .pop() – removes the element at the top of the stack and returns it as the value of the function
• .peek() – looks at the element at the top of the stack without removing it
• .empty() – Boolean function to test if the stack is empty or not. Returns a 0 or 1.
• .search(Object o) – Looks for o and returns its position. The value is 1-based, not 0-based
Stack also inherits all of the methods that are part of Vector, including but not limited to, toString(), contains(), indexOf(), and lastElement().

## Coding a Java Stack Example

Now that we know the functions for the Stack, let’s code a java stack example. Stacks are very useful for handling data that must be stored temporarily and retrieved quickly. Because the Stack is LIFO, it’s exceptionally useful for node traversal when exploring a tree data structure. Before we get into all of that, let’s create a basic stack. The code to implement a stack is as follows:
``````
import java.util.*;

class Main {
public static void main(String[] args) {
Stack<Integer> stackExample = new Stack<Integer>();
``````
That’s all you need to do to create an empty Stack. You can also just declare it simply without declaring a data type by using:
``````
Stack example = new Stack();
``````
Remember that because Stacks are mutable, as we push elements onto the stack, it will automatically adjust in size. Now let’s look at how to use the Stack functions.

## Java Stack Implementation

Let’s look at how to use the five methods we explored briefly earlier. Java stack implementation is easy to remember if you think of it as a stack of plates. You put plates onto the stack, but to get a plate, you don’t go to the bottom, you get one from the top. The last one you put on is the first one you take off. Extending our previous example with stackExample, the functions are as follows:

### Push

``````
// pushing integers onto the Stack
stackExample.push(5);
stackExample.push(10);
``````
At this point, we’re going to show the other functions as if we have pushed these two integers onto the Java stack example every time.

### Pop

``````
//popping integers off of the Stack
System.out.println(stackExample.pop());
System.out.println(stackExample.pop());
``````
Output:
``````
10
5
``````

### IsEmpty

Now, let’s say that you want to remove all of the elements from a Stack but you aren’t sure how many elements there are. You can combine the Boolean.isEmpty() function with a precondition while loop to pop all of the elements from the Stack. Look at how this java stack implementation is done.
``````
while(!stackExample.isEmpty()) {
System.out.println(stackExample.pop());
}
``````
Output
``````
10
5
``````

### Peek

We can use .peek() as stack implementation in Java to take a look at the next item on the Stack without removing it.
``````
System.out.println(stackExample.peek());
``````
Output
``````
10
``````
If we pop and print the Stack, it will return 10 and 5 because the 10 is still on the stack. We just looked at it, we did not remove it with the pop function. The peek function is a great tool for Stacks in java.

### Search

If we want to find a specific element, the stacks implementation in Java uses .search(e); to find it.
``````
System.out.println(stackExample.search(5));
``````
Output
``````
2
``````
Remember that this is because we count from the top of the Stack and Java Stacks start at 1, not 0 like an Array. So, looking at the stack, it is (10) --> (5), and 5 is in the number 2 spot. If you try to find an element that is not in the Stack, you will get a -1 as an output.

### Iterating

When working with any collection, there may be times when you need to look for multiple elements. To save complexity and having to search through the Stack multiple times, you can use iteration. Because Stack in Java extends the List class, there are several options for iterating. One of the easiest is to just use the ListIterator function. ListIterator is nice in that it lets you traverse a Stack from top to bottom or from bottom to top using .hasPrevious() or .hasNext(). Here’s how it looks:
``````
ListIterator<Integer> exampleIterator = stackExample.listIterator(stackExample.size());

while (exampleIterator.hasPrevious()) {
int iteration = exampleIterator.previous();
System.out.println(iteration);
}
``````
Output
``````
10
5
``````
Keep in mind that when you iterate through Stacks in Java, you don’t remove any elements in it. Iterating essentially allows you to peek at every element in the stack in order. When you do this, you can look for locations where certain elements are and then go through and manipulate them. You can count, delete, or even change them if need be.
{"ft_lang_label":"__label__en","ft_lang_prob":0.84643924,"math_prob":0.7955306,"size":5147,"snap":"2023-14-2023-23","text_gpt3_token_len":1154,"char_repetition_ratio":0.15166245,"word_repetition_ratio":0.016968327,"special_character_ratio":0.2286769,"punctuation_ratio":0.12570888,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97273105,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-05-28T03:10:26Z\",\"WARC-Record-ID\":\"<urn:uuid:27fc73ce-12ee-4bf1-9e9c-187bab3d061a>\",\"Content-Length\":\"266451\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:dcdcf081-4c17-4272-8c6a-aea3a8a17774>\",\"WARC-Concurrent-To\":\"<urn:uuid:02fe4dbd-48db-4c99-b4f8-9e191816a4c8>\",\"WARC-IP-Address\":\"18.210.138.7\",\"WARC-Target-URI\":\"https://codegym.cc/groups/posts/190-java-stack-101-delving-into-the-stack-class\",\"WARC-Payload-Digest\":\"sha1:JUZLTTPT6322DDJC7EHZ4ZMKZURBX2CI\",\"WARC-Block-Digest\":\"sha1:CVUFQG5R6NY3HXCCKKMRRUT4SPVYI4XJ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-23/CC-MAIN-2023-23_segments_1685224643462.13_warc_CC-MAIN-20230528015553-20230528045553-00622.warc.gz\"}"}