{"id":7912,"date":"2025-02-27T13:34:11","date_gmt":"2025-02-27T13:34:11","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=7912"},"modified":"2026-04-01T11:55:57","modified_gmt":"2026-04-01T11:55:57","slug":"java-stack","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-stack\/","title":{"rendered":"Java Stack: Data Structure and Stack Class in Java"},"content":{"rendered":"<p>A Java <strong>Stack<\/strong> is one of a number of data structures (collections) for easier data manipulation. As part of our <a href=\"https:\/\/msgprogramator.sk\/en\/data-structures\/\" target=\"_blank\" rel=\"noopener\">series on data structures<\/a>, we&#8217;ll introduce each structure, review its uses, available methods, advantages and disadvantages, and provide tips for when it&#8217;s appropriate to use it.<\/p>\n<p>In this section, we will discuss the collection that represents the stack &#8211; the <strong>Java Stack<\/strong>.<\/p>\n<h2>Java Stack &#8211; data structure introduction<\/h2>\n<p>The Stack collection is implemented as a class in the <em>java.util package<\/em>. It is a descendant of <a href=\"https:\/\/msgprogramator.sk\/en\/?p=7913\" target=\"_blank\" rel=\"noopener\">the Vector class<\/a>, from which it takes its properties and also adds features specific to stack data access.<\/p>\n<figure id=\"attachment_5165\" aria-describedby=\"caption-attachment-5165\" style=\"width: 993px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-5164 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack.webp\" alt=\"Inheritance hierarchy for the Stack collection \" width=\"993\" height=\"1065\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack.webp 993w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack-280x300.webp 280w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack-955x1024.webp 955w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack-768x824.webp 768w\" sizes=\"auto, (max-width: 993px) 100vw, 993px\" \/><figcaption id=\"caption-attachment-5165\" class=\"wp-caption-text\"><strong>Inheritance hierarchy for the Stack collection.<\/strong><br \/>SOURCE: d1jnx9ba8s6j9r.cloudfront.net\/blog\/wp-content\/uploads\/2019\/08\/Stack-Class-in-Java_.jpg<\/figcaption><\/figure>\n<p>The Stack class incorporates the <a href=\"https:\/\/phoenixnap.com\/glossary\/lifo-last-in-first-out#:~:text=LIFO%2C%20which%20stands%20for%20Last,and%20removed%20from%20the%20top.\" target=\"_blank\" rel=\"nofollow noopener\">LIFO (Last In, First Out)<\/a> principle, which means that the last element added is also the first one removed from the stack. This algorithm is useful in situations where we need to keep the order of operations (for example, when computing expressions or implementing recursion) and works in constant time.<\/p>\n<p>A typical example of using Stack is the Stack trace when debugging code. The last visited method is added last to the top of the stack, and when it is exited, it is removed from the stack and the method that called the previous method is on top of the stack.<\/p>\n<p>Although <strong>Stack class<\/strong> is built on top of the Vector class and inherits its dynamic behavior (automatic capacity increase), it is a structure that is currently less used in modern applications because the <strong>Deque<\/strong> interface and its implementations such as <strong>ArrayDeque<\/strong> from java.util can completely replace Stack with its implementation of the LIFO approach and a complete and consistent set of operations.<\/p>\n<h2>Stack class constructor<\/h2>\n<p>The Stack class provides a single simple constructor that creates an empty stack. The capacity of the stack is initially set to a fixed value of 10, and like a vector, it doubles in size when the total size of the stack is exceeded. The difference with the vector is that it never shrinks once elements are removed from the stack.<\/p>\n<p><strong>Empty stack<\/strong><\/p>\n<p>Creates an empty stack with a capacity of 10 (default value).<\/p>\n<h2>Basic operations with the Stack collection<\/h2>\n<p>Basic operations with the Stack collection include:<\/p>\n<h3>Inserting elements (push)<\/h3>\n<p>Adds a new element to the top of the stack.<\/p>\n<h3>Removing an element (pop)<\/h3>\n<p>Removes and returns the top element. If this operation is called on an empty stack, throws an exception <em><strong>EmptyStackException<\/strong><\/em>.<\/p>\n<h3>View of the top element (peek)<\/h3>\n<p>Returns the top element without removing it.<\/p>\n<h3>Check if the stack is empty<\/h3>\n<p>Returns <em>true<\/em> if the stack contains no elements, <em>false<\/em> otherwise.<\/p>\n<h3>Element search (search)<\/h3>\n<p>Searches for an element and returns its distance from the top of the stack. The distance of the topmost element is 1. The one below it is 2, and so on. If the element is not found, it returns -1.<\/p>\n<h2>Java Stack: examples of basic operations<\/h2>\n<h3>Adding elements<\/h3>\n<p>Adding elements to the stack can be done one element at a time or in bulk.<\/p>\n<p><strong>Adding one element <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.push(1);<\/code><\/pre>\n<p><strong>Adding multiple elements at once <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">List&lt;Integer&gt; values = Arrays.asList(2, 3, 4, 5);\nstack.addAll(values);<\/code><\/pre>\n<h3>View of the top element<\/h3>\n<p>If we want to see which element is currently at the top of the stack we use the peek() method.<\/p>\n<p><strong>Information about the top element<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.peek();<\/code><\/pre>\n<p><strong>In our example, it returns the value 5.<\/strong><\/p>\n<h3>Checking if the stack is empty<\/h3>\n<p>If we are interested in whether the stack contains any elements at all, we can call the empty() method.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.empty();<\/code><\/pre>\n<p>In our example, it will return false as it contains elements.<\/p>\n<h3>Searching for elements<\/h3>\n<p>If we want to find out if the stack contains a particular element X, we can call the search(X) method.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.search(X);<\/code><\/pre>\n<p>stack.search(7) =&gt; returns -1<\/p>\n<p>stack.search(2) =&gt; returns 4<\/p>\n<h3>Removal of elements<\/h3>\n<p>Most often we need to remove the top element of the stack &#8211; we do this by calling the pop() method. However, operations from the Vector class offer us other possibilities.<\/p>\n<p><strong>Removing and returning the top element <\/strong><\/p>\n<p>In our example, it removes the top element from the stack (5) and stores it in a variable element. The top of the stack will contain the current element 4.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Integer element = stack.pop();<\/code><\/pre>\n<p><strong>Clearing the stack<\/strong><\/p>\n<p>There are two equivalent methods to clear all stack elements: clear(), removeAllElements().<\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.removeAllElements();\nstack.clear();<\/code><\/pre>\n<h2>Other operations<\/h2>\n<p>I will mention a few other useful methods.<\/p>\n<p><strong>Removing elements using a filter (lambda expression) <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.removeIf(elem -&gt; elem &lt; 2);<\/code><\/pre>\n<p><strong>Detecting the number of elements in the stack <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">int size = stack.size();<\/code><\/pre>\n<p><strong>Index of occurrence of the element closest to the top of the stack <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">stack.lastIndexOf(3);<\/code><\/pre>\n<h2>Documentation of methods for the Stack collection<\/h2>\n<p>A complete overview of all available methods for Stack can be found here &#8211; <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/23\/docs\/api\/java.base\/java\/util\/Stack.html#method-summary\" target=\"_blank\" rel=\"nofollow noopener\">Stack class documentation.<\/a><\/p>\n<h2>Advantages and disadvantages of the Stack data structure<\/h2>\n<h3>Benefits of Stack:<\/h3>\n<ul>\n<li>Simple implementation of the LIFO principle.<\/li>\n<li>Synchronization allows use in a multi-threaded environment.<\/li>\n<li>Derivation from the Vector class adds dynamic behavior and additional data manipulation methods to the stack.<\/li>\n<\/ul>\n<h3>Disadvantages of Stack:<\/h3>\n<ul>\n<li>Low performance compared to modern data structures like ArrayDeque.<\/li>\n<li>Synchronization can be unnecessary and inefficient in applications where it is not required.<\/li>\n<li>Rarely used in modern Java.<\/li>\n<\/ul>\n<h2>When to use Stack in Java?<\/h2>\n<p>The use of the Stack collection is useful in situations where it is necessary to implement algorithms based on the LIFO principle, e.g. in graph traversal,<a href=\"https:\/\/en.wikipedia.org\/wiki\/Backtracking\" target=\"_blank\" rel=\"nofollow noopener\">backtracking<\/a>, can be used in text editors to implement undo and redo operations, manage web browser history and navigate back\/forward, etc.<\/p>\n<p>It can also be used as a synchronized collection in a multi-threaded application where multiple threads are working with the same stack, or used in older applications that use synchronized data structures but still run on an outdated version of Java.<\/p>\n<h2>Example of using Stack in a Java program<\/h2>\n<p>Now that we know the basic methods for the Stack collection, we can play around with them a bit in the following program, which demonstrates the use of the stack to evaluate expressions using Reverse Polish Notation (RPN).<\/p>\n<p><span style=\"text-decoration: underline;\"><strong>Main.java<\/strong><\/span><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import java.util.Arrays;\nimport java.util.Stack;\n\npublic class Main {\n    public static void main(String[] args) {\n        String[] expression = {&quot;2&quot;, &quot;3&quot;, &quot;+&quot;, &quot;4&quot;, &quot;*&quot;};\n        evaluateRPN(expression);\n    }\n\n    public static void evaluateRPN(String[] tokens) {\n        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();\n        System.out.println(&quot;Je zasobnik prazdny? &quot; + stack.empty());\n        System.out.println(&quot;Vypocet RPN pre vyraz: &quot; + Arrays.toString(tokens));\n\n        for (String token : tokens) {\n            if (&quot;+-*\/&quot;.contains(token)) {\n                System.out.println(&quot;Vrchny prvok (peek): &quot; + stack.peek());\n                int b = stack.pop();\n                System.out.println(&quot;Odstraneny pravy operand (pop): &quot; + b);\n\n                int a = stack.pop();\n                System.out.println(&quot;Odstraneny lavy operand (pop): &quot; + a);\n                System.out.println(&quot;Operacia: &quot; + token);\n                switch (token) {\n                    case &quot;+&quot; -&gt; stack.push(a + b);\n                    case &quot;-&quot; -&gt; stack.push(a - b);\n                    case &quot;*&quot; -&gt; stack.push(a * b);\n                    case &quot;\/&quot; -&gt; stack.push(a \/ b);\n                }\n\n                int topValue = stack.peek();\n                System.out.println(&quot;Pridany vysledok (push): &quot; + topValue);\n            } else {\n                stack.push(Integer.parseInt(token));\n                System.out.println(&quot;Pridany prvok (push): &quot; + token + &quot; -&gt; &quot; + stack);\n            }\n        }\n\n        System.out.println(&quot;Je zasobnik prazdny? &quot; + stack.empty());\n        System.out.println(&quot;Hladanie (vzdialenosti) prvku 10 (search): &quot; + stack.search(10));\n        System.out.println(&quot;Hladanie (vzdialenosti) prvku 20 (search): &quot; + stack.search(20));\n        System.out.println(&quot;Konecny vysledok (pop): &quot; + stack.pop());\n        System.out.println(&quot;Je zasobnik prazdny? &quot; + stack.empty());\n    }\n}<\/code><\/pre>\n<p><strong>The output of this example is:<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-5173\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack-vystup-prikladu.webp\" alt=\"The output of the Java Stack example.\" width=\"385\" height=\"521\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack-vystup-prikladu.webp 385w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/java-stack-vystup-prikladu-222x300.webp 222w\" sizes=\"auto, (max-width: 385px) 100vw, 385px\" \/><\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java:<\/p>\n<p><a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/Stack.zip\" target=\"_blank\" rel=\"nofollow noopener\">Download the Stack code example in Java.<\/a><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Stack class uses the LIFO (Last In, First Out) principle, which is the basis of the Stack trace when debugging code &#8211; learn more about the Java Stack collection!<\/p>\n","protected":false},"author":14,"featured_media":5168,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-7912","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7912","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=7912"}],"version-history":[{"count":2,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7912\/revisions"}],"predecessor-version":[{"id":42903,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7912\/revisions\/42903"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/5168"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=7912"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=7912"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=7912"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}