[Go to site: main page, start]

0% found this document useful (0 votes)
9 views10 pages

Understanding Java Stack Class

The document provides an overview of the Java Stack class, a linear data structure that follows Last-In-First-Out (LIFO) principles. It details the class's methods, including push, pop, peek, and search, along with examples of how to implement and use these methods in Java programs. Additionally, it covers stack operations such as checking if the stack is empty, determining its size, and iterating through its elements.

Uploaded by

mondalrathin25xy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Understanding Java Stack Class

The document provides an overview of the Java Stack class, a linear data structure that follows Last-In-First-Out (LIFO) principles. It details the class's methods, including push, pop, peek, and search, along with examples of how to implement and use these methods in Java programs. Additionally, it covers stack operations such as checking if the stack is empty, determining its size, and iterating through its elements.

Uploaded by

mondalrathin25xy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Stack

The stack is a linear data structure that is used to store the collection of objects. It is based
on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and
classes to store the collection of objects. One of them is the Stack class that provides different
operations such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the stack
data structure in a Java program. But before moving to the Java Stack class have a quick view
of how the stack works.
The stack data structure has the two most important operations that are push and pop. The push
operation inserts an element into the stack and pop operation removes an element from the top
of the stack. Let's see how they work on stack.

Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Let's remove (pop) 18, 45, and 11 from the stack.

Empty Stack: If the stack has no element is known as an empty stack. When the stack is
empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following figure,
o Push 12, top=0
o Push 6, top=1
o Push 9, top=2

When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9.

The following table shows the different values of the top.


Java Stack Class
In Java, Stack is a class that falls under the Collection framework that extends
the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable,
Serializable. It represents the LIFO stack of objects. Before using the Stack class, we must
import the [Link] package. The stack class arranged in the Collections framework hierarchy,
as shown below.

Stack Class Constructor


The Stack class contains only the default constructor that creates an empty stack.
1. public Stack()

Creating a Stack
If we want to create a stack, first, import the [Link] package and create an object of the Stack
class.
1. Stack stk = new Stack();
Or
1. Stack<type> stk = new Stack<>();
Where type denotes the type of stack like Integer, String, etc.

Methods of the Stack Class


We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides all
the methods of the Java Vector class.
Method Modifier and Method Description
Type
empty() boolean The method checks the stack is empty or not.
push(E item) E The method pushes (insert) an element onto the top of the stack.
pop() E The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without removing
it.
search(Object int The method searches the specified object and returns the position
o) of the object.
Stack Class empty() Method
The empty() method of the Stack class check the stack is empty or not. If the stack is empty,
it returns true, else returns false. We can also use the isEmpty() method of the Vector class.
Syntax
1. public boolean empty()

Returns: The method returns true if the stack is empty, else returns false.
In the following example, we have created an instance of the Stack class. After that, we have
invoked the empty() method two times. The first time it returns true because we have not
pushed any element into the stack. After that, we have pushed elements into the stack. Again
we have invoked the empty() method that returns false because the stack is not empty.
[Link]
1. import [Link];
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = [Link]();
10. [Link]("Is the stack empty? " + result);
11. // pushing elements into stack
12. [Link](78);
13. [Link](113);
14. [Link](90);
15. [Link](120);
16. //prints elements of the stack
17. [Link]("Elements in Stack: " + stk);
18. result = [Link]();
19. [Link]("Is the stack empty? " + result);
20. }
21. }
Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false

Stack Class push() Method


The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to be pushed
into the stack.
Syntax
1. public E push(E item)
Parameter: An item to be pushed onto the top of the stack.
Returns: The method returns the argument that we have passed as a parameter.

Stack Class pop() Method


The method removes an object at the top of the stack and returns the same object. It
throws EmptyStackException if the stack is empty.
Syntax
1. public E pop()
Returns: It returns an object that is at the top of the stack.
Let's implement the stack in a Java program and perform push and pop operations.

[Link]
1. import [Link].*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. [Link]("stack: " + stk);
9. //pushing elements into the stack
10. pushelmnt(stk, 20);
11. pushelmnt(stk, 13);
12. pushelmnt(stk, 89);
13. pushelmnt(stk, 90);
14. pushelmnt(stk, 11);
15. pushelmnt(stk, 45);
16. pushelmnt(stk, 18);
17. //popping elements from the stack
18. popelmnt(stk);
19. popelmnt(stk);
20. //throws exception if the stack is empty
21. try
22. {
23. popelmnt(stk);
24. }
25. catch (EmptyStackException e)
26. {
27. [Link]("empty stack");
28. }
29. }
30. //performing push operation
31. static void pushelmnt(Stack stk, int x)
32. {
33. //invoking push() method
34. [Link](new Integer(x));
35. [Link]("push -> " + x);
36. //prints modified stack
37. [Link]("stack: " + stk);
38. }
39. //performing pop operation
40. static void popelmnt(Stack stk)
41. {
42. [Link]("pop -> ");
43. //invoking pop() method
44. Integer x = (Integer) [Link]();
45. [Link](x);
46. //prints modified stack
47. [Link]("stack: " + stk);
48. }
49. }
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]

Stack Class peek() Method


It looks at the element that is at the top in the stack. It also throws EmptyStackException if
the stack is empty.
Syntax
1. public E peek()
Returns: It returns the top elements of the stack.
Let's see an example of the peek() method.
[Link]
1. import [Link];
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. [Link]("Apple");
9. [Link]("Grapes");
10. [Link]("Mango");
11. [Link]("Orange");
12. [Link]("Stack: " + stk);
13. // Access element from the top of the stack
14. String fruits = [Link]();
15. //prints stack
16. [Link]("Element at top: " + fruits);
17. }
18. }
Output:
Stack: [Apple, Grapes, Mango, Orange]
Element at the top of the stack: Orange

Stack Class search() Method


The method searches the object in the stack from the top. It parses a parameter that we want to
search for. It returns the 1-based location of the object in the stack. Thes topmost object of the
stack is considered at distance 1.
Suppose, o is an object in the stack that we want to search for. The method returns the distance
from the top of the stack of the occurrence nearest the top of the stack. It uses equals() method
to search an object in the stack.
Syntax
1. public int search(Object o)
Parameter: o is the desired object to be searched.
Returns: It returns the object location from the top of the stack. If it returns -1, it means that
the object is not on the stack.
Let's see an example of the search() method.
[Link]
1. import [Link];
2. public class StackSearchMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. //pushing elements into Stack
8. [Link]("Mac Book");
9. [Link]("HP");
10. [Link]("DELL");
11. [Link]("Asus");
12. [Link]("Stack: " + stk);
13. // Search an element
14. int location = [Link]("HP");
15. [Link]("Location of Dell: " + location);
16. }
17. }

Java Stack Operations


Size of the Stack
We can also find the size of the stack using the size() method of the Vector class. It returns the
total number of elements (size of the stack) in the stack.
Syntax
1. public int size()
Let's see an example of the size() method of the Vector class.
[Link]
1. import [Link];
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. [Link](22);
8. [Link](33);
9. [Link](44);
10. [Link](55);
11. [Link](66);
12. // Checks the Stack is empty or not
13. boolean rslt=[Link]();
14. [Link]("Is the stack empty or not? " +rslt);
15. // Find the size of the Stack
16. int x=[Link]();
17. [Link]("The stack size is: "+x);
18. }
19. }
Output:
Is the stack empty or not? false
The stack size is: 5

Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack using three
different methods are as follows:
o Using iterator() Method
o Using forEach() Method
o Using listIterator() Method
Using the iterator() Method
It is the method of the Iterator interface. It returns an iterator over the elements in the stack.
Before using the iterator() method import the [Link] package.
Syntax
1. Iterator<T> iterator()
Let's perform an iteration over the stack.
[Link]
1. import [Link];
2. import [Link];
3. public class StackIterationExample1
4. {
5. public static void main (String[] args)
6. {
7. //creating an object of Stack class
8. Stack stk = new Stack();
9. //pushing elements into stack
10. [Link]("BMW");
11. [Link]("Audi");
12. [Link]("Ferrari");
13. [Link]("Bugatti");
14. [Link]("Jaguar");
15. //iteration over the stack
16. Iterator iterator = [Link]();
17. while([Link]())
18. {
19. Object values = [Link]();
20. [Link](values);
21. }
22. }
23. }
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar

Using the forEach() Method


Java provides a forEach() method to iterate over the elements. The method is defined in
the Iterable and Stream interface.
Syntax
1. default void forEach(Consumer<super T>action)
Let's iterate over the stack using the forEach() method.
[Link]
1. import [Link].*;
2. public class StackIterationExample2
3. {
4. public static void main (String[] args)
5. {
6. //creating an instance of Stack class
7. Stack <Integer> stk = new Stack<>();
8. //pushing elements into stack
9. [Link](119);
10. [Link](203);
11. [Link](988);
12. [Link]("Iteration over the stack using forEach() Method:");
13. //invoking forEach() method for iteration over the stack
14. [Link](n ->
15. {
16. [Link](n);
17. });
18. }
19. }
Output:
Iteration over the stack using forEach() Method:
119
203
988

Using listIterator() Method


This method returns a list iterator over the elements in the mentioned list (in sequence), starting
at the specified position in the list. It iterates the stack from top to bottom.
Syntax
1. ListIterator listIterator(int index)
Parameter: The method parses a parameter named index.
Returns: This method returns a list iterator over the elements, in sequence.
Exception: It throws IndexOutOfBoundsException if the index is out of range.
Let's iterate over the stack using the listIterator() method.
[Link]
1. import [Link];
2. import [Link];
3. import [Link];
4.
5. public class StackIterationExample3
6. {
7. public static void main (String[] args)
8. {
9. Stack <Integer> stk = new Stack<>();
10. [Link](119);
11. [Link](203);
12. [Link](988);
13. ListIterator<Integer> ListIterator = [Link]([Link]());
14. [Link]("Iteration over the Stack from top to bottom:");
15. while ([Link]())
16. {
17. Integer avg = [Link]();
18. [Link](avg);
19. }
20. }
21. }
Output:
Iteration over the Stack from top to bottom:
988
203
119

Common questions

Powered by AI

The size() method is used to determine the number of elements in the stack, providing insight into the stack's content beyond just checking whether it's empty . It's particularly useful when the operation depends on the count of elements in the stack, such as when performing batch operations on subsets of stack items or when monitoring resource usage associated with stack storage in memory-intensive applications. In contrast, the empty() method only checks if the stack has no elements, which is generally used to avoid errors during pop operations .

A stack is a linear data structure based on Last-In-First-Out (LIFO) order. The primary operations are 'push' and 'pop'. In Java, these are implemented in the Stack class, which is part of the Java Collection Framework. The 'push' operation inserts an element onto the top of the stack with the function signature `public E push(E item)`, and the stack adjusts such that the newly added item is now on top . The 'pop' operation removes the element that is currently on top of the stack and returns it. This method throws an EmptyStackException if the stack is empty when the operation is attempted .

Java provides several methods for iterating over stack elements: using iterator(), forEach(), and listIterator(). The iterator() method returns an iterator that traverses the stack from bottom to top sequentially, allowing operations on each element individually . The forEach() method allows lambda functions to be applied to each element, offering a more declarative way to process stack items . The listIterator() method permits iteration from any specified index, enabling complex traversal patterns such as reverse order, particularly useful in situations like displaying actions in reverse order in undo functionalities . Each method serves different needs, allowing flexibility in stack operations depending on the iteration requirements.

The use of 1-based indexing in the search() method of the Java Stack class implies that the indexing logic in applications utilizing this method must account for this when interacting with other Java collection classes or when integrating into new code, which typically use 0-based indexing . This design choice can introduce an off-by-one error risk if developers don't adjust their indexing expectations accordingly. Additionally, it aligns more with natural counting which could be easier to interpret in stack-specific contexts, but it demands careful attention when transitioning between different collection operations or comparing with external systems not using 1-based patterns .

Using Java's Stack class offers benefits such as out-of-the-box functionality with standard operations (push, pop, peek) and integration into the Java Collections Framework, allowing for interoperability with existing collection methods and utilities . However, it comes with trade-offs such as the overhead inherent in its inheritance from Vector, like synchronization which can impact performance in single-threaded contexts. Custom implementations can optimize memory use, control over element access time, and better performance in terms of operation execution or thread safety. These custom stacks can be implemented using underlying data structures like linked lists or arrays with different trade-offs in terms of performance, memory needs, and complexity of implementation .

The Stack class in Java is a subclass of Vector, which provides it with certain inherited features such as dynamic resizing and synchronization . However, Stack is distinguished by its LIFO (Last-In-First-Out) ordering, tailored specifically with methods to support stack operations like push, pop, and peek. In its inheritance structure, the Stack class extends Vector and also implements interfaces such as List, Collection, Iterable, Cloneable, and Serializable. This makes Stack suitable for certain specific use-cases where LIFO behavior is required, but it generally lacks many of the more advanced features found in other modern collections such as Deques or custom implementations of stacks that might use linked lists instead .

The Java Stack class handles errors during the 'pop' operation on an empty stack by throwing an EmptyStackException. This exception is unchecked and occurs when there is an attempt to perform a 'pop' operation on an empty stack, which means trying to remove an item from a stack that has no elements. It is crucial to ensure that stack operations are wrapped in appropriate exception handling blocks or that checks are performed using methods like empty() before attempting a 'pop' to prevent runtime errors .

The 'peek' method in a Java stack looks at the top element without removing it and returns this element . This can be useful in scenarios where you need to read the current state or value at the top without modifying the stack, such as in expression evaluations where peeking can help decide the next operation based on the topmost operator or operand. For instance, while implementing an undo functionality in applications, peek may help check the most recent action before deciding whether it warrants an undo .

The 'search()' method in the Java Stack class searches for a specific object in the stack and returns its position from the top of the stack, using a 1-based index . If the object is not found, the method returns -1. This method can be particularly useful in algorithms where quick access to a recent similar state is necessary, such as finding a recent occurrence of a specific configuration or checkpoint in algorithm backtracking or debugging with call stack traces .

The 'empty()' method in Java plays a crucial role in error prevention by providing a mechanism to safely check whether a stack contains any elements before attempting operations that would otherwise fail on an empty stack. By returning a boolean, it allows the code to conditionally execute stack operations like 'pop' only when it is safe to do so, thus preventing runtime errors such as EmptyStackException. In practice, this method is essential in ensuring robustness, as revealed through the avoidance of critical failures in environments that make heavy use of stack operations, such as parsing, expression evaluation, or backtracking algorithms .

You might also like